Why is an exception raised? - java

The task: Send "Hello world" from an android device to a MQTT server.
The lib: PahoMqtt 3.1.1
IDE: Android Studio 3.5
Manifest permissions:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
Android's code:
private String topic = "Lesson_MQTT_server";
private String broker = "tcp://[host]:[port];
private char [] pass = "the_password".toCharArray(); // Fake pass
private String user = "the_user";
private String userId = "the_user_id";
private String content = "Hello world from android device!";
private int qos = 2;
private MqttMessage message;
private MqttConnectOptions options;
private MqttClient client;
private TextView info;
private Button clickButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = (TextView)findViewById(R.id.HelloWorld);
clickButton = (Button)findViewById(R.id.MyButton);
clickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
message = new MqttMessage();
message.clearPayload();
message.setPayload(content.getBytes());
message.setQos(qos);
message.setRetained(true);
options = new MqttConnectOptions();
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
options.setAutomaticReconnect(false);
options.setCleanSession(false);
options.setUserName(userId);
options.setPassword(pass);
client = new MqttClient (broker, user);
client.connect(options);
client.publish(topic, message);
client.disconnect(10);
client.close();
info.setText("Check your server:)");
} catch (MqttException ex){
info.setText("Ops! Something went wrong :)");
}
}
});
The problem: MqttException caused.
My observations: This code works fine if I use eclipse IDE.
MqttExceptions: CAUSE: null, Reason CODE: 0, Message: MqttException.

Related

java.lang.IllegalArgumentException: You cannot keep your settings in the secure settings

I am working on Android 12 (AOSP 12) device.
Trying to set the static IP from my application.
Snipped code below:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private static final String KEY_ETH_IP_ADDRESS = "ethernet_ip_addr";
private static final String KEY_ETH_HW_ADDRESS = "ethernet_hw_addr";
private static final String KEY_ETH_NET_MASK = "ethernet_netmask";
private static final String KEY_ETH_GATEWAY = "ethernet_gateway";
private static final String KEY_ETH_DNS1 = "ethernet_dns1";
private static final String KEY_ETH_DNS2 = "ethernet_dns2";
private static final String KEY_ETH_MODE = "ethernet_mode_select";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.System.canWrite(this)) {
Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT).show();
ContentResolver cr = this.getContentResolver();
Settings.System.putString(cr,KEY_ETH_IP_ADDRESS, "10.xxx.xxx.15");
Settings.System.putString(cr,KEY_ETH_NET_MASK, "255.255.255.100");
Settings.System.putString(cr,KEY_ETH_GATEWAY, "10.xx.xx.100");
Settings.System.putString(cr,KEY_ETH_DNS1, "10.xxx.xx.10");
Settings.System.putString(cr,KEY_ETH_DNS2, "10.xxx.xx.10");
} else {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" + this.getPackageName()));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
Given below permission in AndroidManifest.xml file :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:ignore="CoarseFineLocation" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS" tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" tools:ignore="ProtectedPermissions" />
Error:
java.lang.IllegalArgumentException: You cannot keep your settings in the secure settings.
at com.android.providers.settings.SettingsProvider.warnOrThrowForUndesiredSecureSettingsMutationForTargetSdk(SettingsProvider.java:2266)
at com.android.providers.settings.SettingsProvider.enforceRestrictedSystemSettingsMutationForCallingPackage(SettingsProvider.java:2036)
at com.android.providers.settings.SettingsProvider.mutateSystemSetting(SettingsProvider.java:1889)
at com.android.providers.settings.SettingsProvider.insertSystemSetting(SettingsProvider.java:1840)
at com.android.providers.settings.SettingsProvider.call(SettingsProvider.java:462)
...
Process: com.xxx.test_staticip, PID: 3267
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxx.test_staticip/com.xxx.test_staticip.MainActivity}: java.lang.IllegalArgumentException: You cannot keep your settings in the secure settings.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3707)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3864)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2253)
...
Caused by: java.lang.IllegalArgumentException: You cannot keep your settings in the secure settings.
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:172)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:142)
at android.content.ContentProviderProxy.call(ContentProviderNative.java:732)
at android.provider.Settings$NameValueCache.putStringForUser(Settings.java:2867)
at android.provider.Settings$System.putStringForUser(Settings.java:3572)
at android.provider.Settings$System.putStringForUser(Settings.java:3556)
at android.provider.Settings$System.putString(Settings.java:3529)
at com.xxx.test_staticip.MainActivity.onCreate(MainActivity.java:84)
at android.app.Activity.performCreate(Activity.java:8072)
at android.app.Activity.performCreate(Activity.java:8052)
...
I couldn't found proper info on Google, some solutions are very old and those are deprecated in Android 12.

How to get BLE devices' names list by android app?

Hello I am making a bluetooth connecting android app.
I followed the instruction from developer.android.com
while I am testing my app, I look forward to it works properly, but it didn't.
I tried to get detected BLE devices names, but don't know the reason why it doesn't show me the devices name...
Arduino nano 33 IOT is adverstising bluetooth next to my android phone, and I am trying to detect it and get the Adrduino's BLE device name and address.
here is my MainActivity.java
public class MainActivity extends AppCompatActivity {
//View Contents Elements
public Button btnActivateBluetooth;
public Button btnSearchBluetooth;
public Button btnSendData;
public ListView lvSearchedDevice;
public ListView lvLog;
public TextView tvStatus;
public EditText etData;
//etc values
public ArrayAdapter<String> logAdapter;
private final int REQUEST_ENABLE_BT = 1;
private boolean mScanning = true;
//bluetooth values
public BluetoothAdapter btAdapter;
public BluetoothManager btManager;
private Handler handler;
#SuppressLint("MissingPermission")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//View Elements
btnSearchBluetooth = (Button) findViewById(R.id.btnSearchBluetooth);
btnSendData = (Button) findViewById(R.id.btnSendData);
lvSearchedDevice = (ListView) findViewById(R.id.lvSearchedDevice);
lvLog = (ListView) findViewById(R.id.log);
tvStatus = (TextView) findViewById(R.id.tvStatus);
etData = (EditText) findViewById(R.id.etData);
//etc
logAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
lvLog.setAdapter(logAdapter);
handler = new Handler();
// Initializes Bluetooth adapter.
btManager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = btManager.getAdapter();
// displays a dialog requesting user permission to enable Bluetooth.
if (btAdapter == null || !btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
btnSearchBluetooth.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanLeDevice(true);
}
});
}
//Scan devices
#SuppressLint("MissingPermission")
private void scanLeDevice(final boolean enable){
if(enable){
handler.postDelayed(new Runnable() {
#SuppressLint("MissingPermission")
#Override
public void run() {
btAdapter.stopLeScan(leScanCallback);
}
},5000);
btAdapter.startLeScan(leScanCallback);
}
else
{
btAdapter.stopLeScan(leScanCallback);
}
}
//Callback method
private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#SuppressLint("MissingPermission")
#Override
public void run() {
Toast.makeText(MainActivity.this, device.getName(), Toast.LENGTH_SHORT).show();
}
});
}
};
}
and this is my Arduino nano 33 IOT's code.
#include <ArduinoBLE.h>
BLEService Toothbrush("00001101-0000-1000-8000-00805F9B34FB");
BLEStringCharacteristic ToothbrushChar("00001101-0000-1000-8000-00805F9B34FB",BLEWrite|BLERead | BLENotify, 10);
void setup() {
Serial.begin(9600);
if(!BLE.begin()){
Serial.println("Starting BLE failed.");
while(1);
}
BLE.setLocalName("HayanToothbrush");
BLE.setAdvertisedService(Toothbrush);
Toothbrush.addCharacteristic(ToothbrushChar);
BLE.addService(Toothbrush);
BLE.advertise();
Serial.println("Bluetooth device active, wating for connections...");
}
void loop() {
BLEDevice central = BLE.central();
if(central) {
Serial.print("Connected to central : ");
Serial.println(central.address());
while(central.connected()){
}
Serial.print("Disconnected from central:");
Serial.println(central.address());
}
}
I add permissions in the Mainfest as below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.bluetooth0523">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
<application
android:allowBackup="true"
android:dataExtractionRules="#xml/data_extraction_rules"
android:fullBackupContent="#xml/backup_rules"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Bluetooth0523"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
But it still doesn't find me scanned device name.
I think it's on LeScanCallBack problem.
When running startLeScan, It seems not running callback method.
in addition, I am running this app on SDK_VERSION_30
and Arduino nano IOT 33 is discoverable If I use the Bluetooth function that my phone has, not my application, it will be displayed in the scan result list.
I want to get scan result on my own app.
but don't know where is the problem.
Permissions must be declared and requested depending on Android version. Main differences are:
Target Android 12 or higher
BLUETOOTH_SCAN
Target Android 11 or lower
ACCESS_FINE_LOCATION
See Bluetooth permissions for details.

IOException Unable to resolve host,No address associated with hostname

I am working on Sony Remote camera which is connected using WiFi.I need to click a picture using a camera and then upload it to my FTP server which is in another activity.for than I need to disconnect my camera wifi and connect to the another wifi network or mobile data.when I connect to the another wifi/mobile data and going to upload the picture on FTP server I got this error.
IOException Unable to resolve host No address associated with hostname
When a close application and start again, And then directly upload pictures without connecting/disconnection camera than it works fine.
someone, please tell me how can I solve this, because I checked each and every solution on stack overflow and not one solution work for me.
I added bellow permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
Connection to a network is not inmediate.
Also, if the desired network has no internet connection, in recent versions of Android it will not connect (if the connection is made by a user, a popup shows a confirmation to connnect).
I solved both problems using Android APIs (2 versions, one for API<21 and the other for API>=21).
Try this code (I'm using AndroidAnnotations for dependency injection, but is not required):
public class WifiHelper extends BroadcastReceiver {
#RootContext
Context context;
#SystemService
ConnectivityManager connectivityManager;
#SystemService
WifiManager wifiManager;
// For API>=21
private WifiHelperNetworkCallback wnc;
// For API<21
private boolean isBroadcastRegistered;
private String desiredSSID;
private Runnable callback;
public void enableNetwork(String ssid, int networkId, Runnable callback) {
desiredSSID = ssid;
wifiManager.enableNetwork(networkId, true);
configureNetworkRequest();
}
private void networkAvailable() {
// this method will be called when the network is available
callback.run();
}
private void configureNetworkRequest() {
if (android.os.Build.VERSION.SDK_INT >= 21) {
configureNetworkRequestAPI21();
} else {
configureNetworkRequestLegacy();
}
}
#TargetApi(21)
private void configureNetworkRequestAPI21() {
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();
if (wnc == null) wnc = new WifiHelperNetworkCallback(this, connectivityManager);
connectivityManager.requestNetwork(request, wnc);
}
private void configureNetworkRequestLegacy() {
unregisterReceiver();
connectivityManager.startUsingNetworkFeature(ConnectivityManager.TYPE_WIFI, null);
IntentFilter intent = new IntentFilter();
intent.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intent.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
context.registerReceiver(this, intent);
isBroadcastRegistered = true;
}
#TargetApi(21)
private void disableNetworkRequest() {
if (android.os.Build.VERSION.SDK_INT >= 21) {
if (wnc != null) connectivityManager.unregisterNetworkCallback(wnc);
ConnectivityManager.setProcessDefaultNetwork(null);
} else {
unregisterReceiver();
}
}
private void unregisterReceiver() {
if (isBroadcastRegistered) {
context.unregisterReceiver(this);
isBroadcastRegistered = false;
}
}
// API<21
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo networkInfo =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if(networkInfo.isConnected()) {
// Wifi is connected
if (desiredSSID.equals(getCurrentSSID())) {
// Callback and unregister
networkAvailable();
unregisterReceiver();
}
}
}
}
public String getCurrentSSID() {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null && wifiInfo.getSupplicantState()== SupplicantState.COMPLETED) {
return ssidWithoutQuotes(wifiInfo.getSSID());
}
else return null;
}
protected static String ssidWithoutQuotes(String ssid) {
if (ssid == null) return null;
else if (ssid.startsWith("\"") && ssid.endsWith("\"")) {
return ssid.substring(1, ssid.length() - 1);
} else {
return ssid;
}
}
protected String getDesiredSSID() {
return desiredSSID;
}
#TargetApi(21)
public static class WifiHelperNetworkCallback extends ConnectivityManager.NetworkCallback {
public final String LOG_TAG = WifiHelper.class.getSimpleName();
private ConnectivityManager connectivityManager;
private WifiHelper wifiHelper;
public WifiHelperNetworkCallback(WifiHelper wifiHelper, ConnectivityManager connectivityManager) {
this.wifiHelper = wifiHelper;
this.connectivityManager = connectivityManager;
}
public void onAvailable(Network network) {
// Do something once the network is available
NetworkInfo info = connectivityManager.getNetworkInfo(network);;
Log.i(LOG_TAG, "networkcallback!! " + info.getExtraInfo());
String desiredSSID = wifiHelper.getDesiredSSID();
if (desiredSSID != null && desiredSSID.equals(ssidWithoutQuotes(info.getExtraInfo()))) {
ConnectivityManager.setProcessDefaultNetwork(network);
wifiHelper.networkAvailable();
}
}
}
}
You will need this permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" android:maxSdkVersion="18"/>

Acquiring and storing accelerometer data on Android Wear smartwatch

I'm trying to acquire accelerometer data using an Android Wear app on a smartwatch (Samsung Gear Live). To acquire that data I use a service which listens to three components:
a SensorEventListener, where the onSensorChanged method triggers a SensorEventLoggerTask that stores the accelerometer data with timestamps in a file on the smartwatch
a System intent that listens to the battery
an Intent that listens button clicks on an activity. The activity is used to annotate the data, so I have an idea at what timestamp an (person)activity (running, eating, sleeping,...) was started:
This works fine and I can sample the data every (more or less) 5-6 ms. However this only works when the smartwatch is connected through adb or when the activity is active (to press a button). From the moment it is not connected anymore, there are gaps in the data. With gaps I mean that the time between two timestamps of accelerometer values is much larger than the 5-6 ms. Going to seconds... The gaps appear irregular. But when the activity becomes active (to press a button) or I connect the smartwatch to the adb, the values are gathered. It appears that the service is paused/sleeps/shut down, when the smartwatch is not active.
Below I post the code. The project consists of two classes WearableActivity and WearableService. Furthermore, I also show the Manifest. Allthough this is only prototyping code, any help in resolving the data gaps or suggestions to the code, would be greatly appreciated.
WearableActivity.java
public class WearableActivity extends Activity {
//Set strings and widgets
private static final String TAG = "WearableActivity";
private TextView mTextView;
private Button[] buttons;
private String[] strings;
#Override
protected void onCreate(Bundle savedInstanceState) {
//setscreen
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wearable);
//check if service is already running
if(this.check() == false)
this.startService(new Intent(this, WearableService.class));
Resources res = this.getResources();
strings = res.getStringArray(R.array.button_names);
buttons = new Button[strings.length];
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
mTextView = (TextView) stub.findViewById(R.id.text);
mTextView.setText("ActiMon_Store Started");
buttons[0] = (Button)stub.findViewById(R.id.button1);
buttons[1] = (Button)stub.findViewById(R.id.button2);
buttons[2] = (Button)stub.findViewById(R.id.button3);
buttons[3] = (Button)stub.findViewById(R.id.button4);
buttons[0].setText(strings[0]);
buttons[1].setText(strings[1]);
buttons[2].setText(strings[2]);
buttons[3].setText(strings[3]);
for(Button b : buttons)
b.setOnClickListener(btnListener);
}
});
}
//---create an anonymous class to act as a button click listener---
private OnClickListener btnListener = new OnClickListener()
{
public void onClick(View v)
{
Intent buttonIntent = new Intent("button_activity");
Button b = (Button)v;
buttonIntent.putExtra("time", Long.toString(System.currentTimeMillis()));
buttonIntent.putExtra("button", b.getText().toString());
sendBroadcast(buttonIntent);
Toast.makeText(getApplicationContext(),
"Event sent", Toast.LENGTH_LONG).show();
}
};
//Checks is the service WearableService already started
public boolean check(){
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if ("com.example.WearableService"
.equals(service.service.getClassName()))
{
Log.i(TAG,"Service already running!");
return true;
}
}
Log.i(TAG,"Service already running!");
return false;
}
}
WearableService.java
public class WearableService extends Service implements SensorEventListener {
private PrintStream ps;
private PrintStream ps_bat;
private PrintStream ps_button;
private String androidpath;
private float[] gravity = new float[3];
private float[] linear_acceleration = new float[3];
private PowerManager pm;
private PowerManager.WakeLock wl;
private SensorManager mSensorManager;
private Sensor mAcceleroSensor;
//Create the service and register the listeners
#Override
public void onCreate(){
super.onCreate();
this.registerListeners();
}
//Registers the SensorManager, the listener to the battery and the intent
private void registerListeners(){
mSensorManager = (SensorManager)this.getSystemService(SENSOR_SERVICE);
mAcceleroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this,mAcceleroSensor,SensorManager.SENSOR_DELAY_FASTEST);
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(battery_receiver, ifilter);
this.registerReceiver(broadcastReceiver, new IntentFilter("button_activity"));
}
//Start service as at STICKY
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
this.getFile();
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE,"KeepCPUWorking");
wl.acquire();
return Service.START_STICKY;
}
//When sensor value has changed
public void onSensorChanged(SensorEvent event){
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
//Perform a background task to store the data
new SensorEventLoggerTask().execute(event);
}
}
//Get handles to files where data has to be stored
public void getFile(){
androidpath = Environment.getExternalStorageDirectory().toString();
try{
ps = new PrintStream(new FileOutputStream(androidpath + "/data_acc.dat"));
ps_bat = new PrintStream(new FileOutputStream(androidpath + "/data_bat.dat"));
ps_button = new PrintStream(new FileOutputStream(androidpath + "/data_button.dat"));
} catch (Exception e){
e.printStackTrace();
}
}
//Create receiver that listens to Intents from the Battery
private BroadcastReceiver battery_receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
int bLevel = arg1.getIntExtra("level", -1); // gets the battery level
int bScale = arg1.getIntExtra("scale", -1);
ps_bat.println("" + System.currentTimeMillis() + ";" + bLevel + ";" + bScale);
}
};
#Override
public void onDestroy(){
if(wl.isHeld()) wl.release();
}
// For receiving the broadcast event of the buttons.
private BroadcastReceiver broadcastReceiver = new
BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("button") + ";" + intent.getStringExtra("time");
ps_button.println(msg);
}
};
//Create a Task that logs events to a file
private class SensorEventLoggerTask extends AsyncTask<SensorEvent, Void, Void>{
#Override
protected Void doInBackground(SensorEvent... events) {
//Getting the event and values
SensorEvent event = events[0];
String msg = "" + event.values[0] + ";" + event.values[1] + ";" + event.values[2];
//constructing the the line
msg = "" + System.currentTimeMillis() + ";" + msg;
//writing to file
ps.println(msg);
return null;
}
}
}
Manifest.xml
`<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wearabledemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature android:name="android.hardware.type.watch" />
<uses-sdk
android:minSdkVersion="20"
android:targetSdkVersion="20" />
<uses-permission android:name="android.permission.BODY_SENSORS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.DeviceDefault" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".WearableActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:enabled="true"
android:name=".WearableService"
android:label="#string/app_name"
android:exported="true"
android:permission="android.permission.WAKE_LOCK" >
</service>
</application>
</manifest>`

Unable to push NdefMessage with 4.x Android NFC API

I am implementing CreateNdefMessageCallback and OnNdefPushCompleteCallback. For some reason the callback methods are NEVER touched, no errors on the log either.
I do hear the sound from the API though, the phone that I am debugging on is a Nexus S running version 4.0.4.
Here is my activity:
public class TestActivity extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback
{
private static SoundHelper soundHelper;
private PowerManager.WakeLock wakeLock;
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent = null;
private IntentFilter[] intentFiltersArray;
private String[][] techListsArray;
private TextView onScreenLog;
private List<String> uniqueTagsRead = new ArrayList<String>();
/** handler stuff */
private static final int MESSAGE_SENT = 1;
private final Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MESSAGE_SENT:
if (soundHelper != null)
{
soundHelper.playSound(R.raw.smw_coin);
}
updateTagCount();
break;
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
soundHelper = new SoundHelper(this);
onScreenLog = (TextView) findViewById(R.id.log);
// nfc adapter
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter != null)
{
// callbacks
nfcAdapter.setNdefPushMessageCallback(this, this);
nfcAdapter.setOnNdefPushCompleteCallback(this, this);
// other stuff
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try
{
ndef.addDataType("*/*");
}
catch (MalformedMimeTypeException e)
{
throw new RuntimeException("fail", e);
}
intentFiltersArray = new IntentFilter[] {ndef, };
techListsArray = new String[][] {
new String[] { IsoDep.class.getName() },
new String[] { NfcA.class.getName() },
new String[] { NfcB.class.getName() },
new String[] { NfcF.class.getName() },
new String[] { NfcV.class.getName() },
new String[] { Ndef.class.getName() },
new String[] { NdefFormatable.class.getName() },
new String[] { MifareClassic.class.getName() },
new String[] { MifareUltralight.class.getName() },
};
}
else
{
onScreenLog.setText("NFC is not available on this device. :(");
}
}
public void onPause()
{
super.onPause();
// end wake lock
wakeLock.release();
nfcAdapter.disableForegroundDispatch(this);
}
public void onResume()
{
super.onResume();
// start wake lock
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");
wakeLock.acquire();
nfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
}
private void updateTagCount()
{
String newCount = String.valueOf(uniqueTagsRead.size());
String text = getString(R.string.format_count);
text = getString(R.string.format_count).replace("0", newCount);
onScreenLog.setText(text);
}
#Override
public NdefMessage createNdefMessage(NfcEvent event)
{
String message = "This is NFC message";
NdefRecord mimeRecord = createMimeRecord("application/param.android.sample.beam",
message.getBytes());
NdefRecord appRecord = NdefRecord.createApplicationRecord("param.android.sample.beam");
NdefRecord[] ndefRecords = new NdefRecord[] {
mimeRecord,
appRecord
};
NdefMessage ndefMessage = new NdefMessage(ndefRecords);
return ndefMessage;
/*
String mimeType = "text/plain"; // "text/plain";
NdefRecord[] data = {createMimeRecord(mimeType, TEXT_TO_WRITE.getBytes())};
// data[data.length - 1] = NdefRecord.createApplicationRecord(); // com.test.nfc.application.activities.
return new NdefMessage(data);
*/
}
/**
* Creates a custom MIME type encapsulated in an NDEF record
*
* #param mimeType
*/
public NdefRecord createMimeRecord(String mimeType, byte[] payload)
{
byte[] mimeBytes = mimeType.getBytes(Charset.forName("US-ASCII"));
NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, new byte[0], payload);
return mimeRecord;
}
#Override
public void onNdefPushComplete(NfcEvent event)
{
handler.obtainMessage(MESSAGE_SENT).sendToTarget();
}
}
manifest:
<uses-sdk android:minSdkVersion="14" />
<supports-screens android:anyDensity="true" />
<uses-permission android:name="android.permission.NFC"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-feature android:name="android.hardware.nfc" />
<application android:name="com.test.nfc.application.Application"
android:icon="#drawable/icon_launcher_nfc_droid_hdpi"
android:theme="#android:style/Theme.Light"
android:label="#string/app_name">
<activity
android:label="#string/app_name"
android:name=".application.activities.MainActivity"
android:configChanges="orientation|keyboardHidden">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:label="#string/test"
android:name=".application.activities.TestActivity"
android:configChanges="orientation|keyboardHidden"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="#xml/nfc_tech_list" />
</activity>
</application>
</manifest>
techlist
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.IsoDep</tech>
<tech>android.nfc.tech.NfcA</tech>
<tech>android.nfc.tech.NfcB</tech>
<tech>android.nfc.tech.NfcF</tech>
<tech>android.nfc.tech.NfcV</tech>
<tech>android.nfc.tech.Ndef</tech>
<tech>android.nfc.tech.NdefFormatable</tech>
<tech>android.nfc.tech.MifareClassic</tech>
<tech>android.nfc.tech.MifareUltralight</tech>
</tech-list>
</resources>
From your question and example code it is not entirely clear to me whether you want to receive NDEF messages, send them or both.
When using NfcAdapter.enableForegroundDispatch(), your Activity will be notified about new NFC intents by a call to onNewIntent(), so you should override that method in your Activity to receive the intents.
NfcAdapter.CreateNdefMessageCallback and NfcAdapter.OnNdefPushCompleteCallback are used to send NDEF data via Android Beam to another NFC device. The user needs to tap the screen to activate sending the NDEF message, which will cause calls to createNdefMessage() and onNdefPushComplete().
One more remark: if you pass null for the filters and techLists parameters to NfcAdapter.enableForegroundDispatch() that will act as a wild card (so you don't need to declare a complete list of technologies, as you are doing now).
It looks like you are getting the default NFC adapter twice?
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
You do it once before your check for null on nfcAdapter, then in your if statement you do it again. This might have some weird effects. I'm not sure though. Also it looks like you are declaring intent filters at runtime. Do this in the manifest to debug if you still have problems. It's just easier to be certain something is filtering intents correctly that way.
See this sample code and the Android Beam sample in the SDK for more examples:
http://developer.android.com/guide/topics/nfc/nfc.html#p2p

Categories