Prevent onDestroy when Bluetooth connection state changes - android

Goal
If an already connected bluetooth device disconnects, and an Activity is already running, close the Activity
Problem
When the bluetooth device connection state changes through BluetoothAdapterProperties: CONNECTION_STATE_CHANGE, it seems like a new Activity is created or the current one restarts.
There is nothing in the code that listens and/or should react to bluetooth connection state changes.
The problem manifests itself in the use of BroadcastReceivers which in turn starts the Activity using intents. For some reason the Activity keep running through its lifecycle, spawning up new windows, even if the only change in bluetooth connectivity is BluetoothAdapterProperties: CONNECTION_STATE_CHANGE
I've tested this solely on a Nexus 6P with Android N. I have no idea yet what kind of implications this implementation means for any other devices yet. But I at least need to get this working on one device.
UPDATE
I have done a fair bit of experimentation and found that if I don't register the BroadcastReceiver in AndroidManifest, the problem with onDestroy being called disappears. But, I want to be able to react to Bluetooth connecting devices, so that I can launch my activity and then process input. If the activity gets destroyed every time a new device connects/disconnects, this won't work at all. What's the reasoning for having the BroadcastReceiver finishing an activity if it's already running and can I control that behaviour?
UPDATE 2
I can also conclude that disabling the statically declared BroadcastReceiver using this method https://stackoverflow.com/a/6529365/975641 doesn't improve things. As soon as the Manifest-BroadcastReceiver catches the ACL_CONNECTED intent from Android, and start my custom activity, it will ruthlessly call onDestroy on it when the connection state changes (which is usually just before an ACL_DISCONNECTED). It does not matter if I have ACL_DISCONNECTED declared in the Manifest or not. As long as I have my receiver listening for ACL_CONNECTED intents and I launch my Activity based on that, onDestroy will be called when the connection state changes. So frustrating.
Manifest
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".BtActivity"
android:launchMode="singleTop" />
<receiver android:name=".BtConnectionBroadcastReceiver" android:priority="100000">
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.intent.action.MEDIA_BUTTON" />
<action android:name="android.media.VOLUME_CHANGED_ACTION" />
</intent-filter>
</receiver>
</application>
BtConnectionBroadcastReceiver
public class BtConnectionBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "BT";
public static final String BROADCAST_ACTION_CONNECTED = "CONNECTED";
public static final String BROADCAST_ACTION_DISCONNECTED = "DISCONNECTED";
SharedPreferences mSharedPreferences;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// Get the BluetoothDevice object from the Intent
Log.d(TAG, "DEVICE CONNECTED");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d("DEVICE NAME", device.getName());
Log.d("DEVICE ADDRESS", device.getAddress());
Intent i = new Intent(context, BtActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(i);
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Log.d(TAG, "DEVICE DISCONNECTED");
intent = new Intent();
intent.setAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
context.sendBroadcast(intent);
}
}
BtActivity
public class BtActivity extends AppCompatActivity {
private static final String TAG = "BT";
Window mWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt);
Log.d(TAG, "onCreate");
IntentFilter filter = new IntentFilter(BtConnectionBroadcastReceiver.INTENT_FILTER);
filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_CONNECTED);
filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
//registerReceiver(mReceiver, filter);
mWindow = getWindow();
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
//params.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
params.screenBrightness = 0.2f;
mWindow.setAttributes(params);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mWindow.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_IMMERSIVE);
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "BROADCAST RECEIVED IN ACTIVITY");
String mac;
if(intent.getAction().equals(BtConnectionBroadcastReceiver.BROADCAST_DEVICE_CONNECTED)) {
Log.d(TAG, "CONNECT BROADCAST RECEIVED");
mac = intent.getStringExtra("mac");
checkConnectedDevice(mac, true); // This adds a device to an internal list
Log.d(TAG, "Activity nr of devices:" +mNrOfDevices);
}
if(intent.getAction().equals(BtConnectionBroadcastReceiver.BROADCAST_DEVICE_DISCONNECTED)) {
Log.d(TAG, "DISCONNECT BROADCAST RECEIVED");
mac = intent.getStringExtra("mac");
checkConnectedDevice(mac, false); // This removes a device from an internal list
Log.d(TAG, "Activity nr of devices:" +mNrOfDevices);
if(mNrOfDevices < 1) {
Log.d(TAG, "No more connected devices");
finish();
}
}
abortBroadcast();
}
};
}
When I run this code, I get the following chain:
Start MainActivity (not included, it only contains an activity with the default main layout, so that the applications receiver is registered)
Switch on a bluetooth device (This has been paired earlier, so android knows about it)
Wait until it connects and get this:
DEVICE CONNECTED
onCreate
onResume
Switch off the bluetooth device and I then get this:
DEVICE DISCONNECTED
onDestroy
onCreate
onResume
I can't grasp why the activity is getting destroyed restarting at this point. The activity is already running, the BroadcastReceiver only sends a broadcast to an already running activity. I can't figure out why there's a reason for the Activity to kill itself and then restart again. This leaves me in a state of the Activity still running, but it is not the original Activity that was started.
I do however see something in the logcats that seem to have something to do with this, and it's in this sequencing;
06-02 15:45:09.156 26431 26431 D BT : DEVICE DISCONNECTED
06-02 15:45:09.213 19547 19547 D BluetoothAdapterService: handleMessage() - MESSAGE_PROFILE_CONNECTION_STATE_CHANGED
06-02 15:45:09.213 26431 26431 D BT : onDestroy
06-02 15:45:09.214 19547 19547 D BluetoothAdapterProperties: CONNECTION_STATE_CHANGE: FF:FF:20:00:C1:47: 2 -> 0
06-02 15:45:09.216 3502 3805 D CachedBluetoothDevice: onProfileStateChanged: profile HID newProfileState 0
06-02 15:45:09.237 414 414 W SurfaceFlinger: couldn't log to binary event log: overflow.
06-02 15:45:09.239 26431 26431 D BT : onCreate
06-02 15:45:09.243 26431 26431 D BT : onResume

In the AndroidManifest.xml add the following for the Activity, it is worked for me.
android:configChanges="keyboard|keyboardHidden"

Having read this https://developer.android.com/guide/components/broadcasts.html#effects_on_process_state I can probably safely conclude that the reason for why onDestroy gets called is because the receiver affects the process in which it is run, effectively meaning when the receiver has run its onReceive method, it will destroy itself and take the Activity with it.
I would of course have wished it was working differently, but I believe this is what effectively is going on and need to take another approach.

I know this answer is very late, but I was facing this issue with my activity tag. In Manifest file I have added below line for configChange.
android:configChanges="keyboard|orientation|screenSize|keyboardHidden|navigation|screenLayout"
Now my application does not kill itself.

Related

Android studio - When connected to a bluetooth device, the onDestroy is called [duplicate]

Goal
If an already connected bluetooth device disconnects, and an Activity is already running, close the Activity
Problem
When the bluetooth device connection state changes through BluetoothAdapterProperties: CONNECTION_STATE_CHANGE, it seems like a new Activity is created or the current one restarts.
There is nothing in the code that listens and/or should react to bluetooth connection state changes.
The problem manifests itself in the use of BroadcastReceivers which in turn starts the Activity using intents. For some reason the Activity keep running through its lifecycle, spawning up new windows, even if the only change in bluetooth connectivity is BluetoothAdapterProperties: CONNECTION_STATE_CHANGE
I've tested this solely on a Nexus 6P with Android N. I have no idea yet what kind of implications this implementation means for any other devices yet. But I at least need to get this working on one device.
UPDATE
I have done a fair bit of experimentation and found that if I don't register the BroadcastReceiver in AndroidManifest, the problem with onDestroy being called disappears. But, I want to be able to react to Bluetooth connecting devices, so that I can launch my activity and then process input. If the activity gets destroyed every time a new device connects/disconnects, this won't work at all. What's the reasoning for having the BroadcastReceiver finishing an activity if it's already running and can I control that behaviour?
UPDATE 2
I can also conclude that disabling the statically declared BroadcastReceiver using this method https://stackoverflow.com/a/6529365/975641 doesn't improve things. As soon as the Manifest-BroadcastReceiver catches the ACL_CONNECTED intent from Android, and start my custom activity, it will ruthlessly call onDestroy on it when the connection state changes (which is usually just before an ACL_DISCONNECTED). It does not matter if I have ACL_DISCONNECTED declared in the Manifest or not. As long as I have my receiver listening for ACL_CONNECTED intents and I launch my Activity based on that, onDestroy will be called when the connection state changes. So frustrating.
Manifest
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".BtActivity"
android:launchMode="singleTop" />
<receiver android:name=".BtConnectionBroadcastReceiver" android:priority="100000">
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.intent.action.MEDIA_BUTTON" />
<action android:name="android.media.VOLUME_CHANGED_ACTION" />
</intent-filter>
</receiver>
</application>
BtConnectionBroadcastReceiver
public class BtConnectionBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "BT";
public static final String BROADCAST_ACTION_CONNECTED = "CONNECTED";
public static final String BROADCAST_ACTION_DISCONNECTED = "DISCONNECTED";
SharedPreferences mSharedPreferences;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// Get the BluetoothDevice object from the Intent
Log.d(TAG, "DEVICE CONNECTED");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d("DEVICE NAME", device.getName());
Log.d("DEVICE ADDRESS", device.getAddress());
Intent i = new Intent(context, BtActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(i);
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Log.d(TAG, "DEVICE DISCONNECTED");
intent = new Intent();
intent.setAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
context.sendBroadcast(intent);
}
}
BtActivity
public class BtActivity extends AppCompatActivity {
private static final String TAG = "BT";
Window mWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt);
Log.d(TAG, "onCreate");
IntentFilter filter = new IntentFilter(BtConnectionBroadcastReceiver.INTENT_FILTER);
filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_CONNECTED);
filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
//registerReceiver(mReceiver, filter);
mWindow = getWindow();
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
//params.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
params.screenBrightness = 0.2f;
mWindow.setAttributes(params);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mWindow.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_IMMERSIVE);
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "BROADCAST RECEIVED IN ACTIVITY");
String mac;
if(intent.getAction().equals(BtConnectionBroadcastReceiver.BROADCAST_DEVICE_CONNECTED)) {
Log.d(TAG, "CONNECT BROADCAST RECEIVED");
mac = intent.getStringExtra("mac");
checkConnectedDevice(mac, true); // This adds a device to an internal list
Log.d(TAG, "Activity nr of devices:" +mNrOfDevices);
}
if(intent.getAction().equals(BtConnectionBroadcastReceiver.BROADCAST_DEVICE_DISCONNECTED)) {
Log.d(TAG, "DISCONNECT BROADCAST RECEIVED");
mac = intent.getStringExtra("mac");
checkConnectedDevice(mac, false); // This removes a device from an internal list
Log.d(TAG, "Activity nr of devices:" +mNrOfDevices);
if(mNrOfDevices < 1) {
Log.d(TAG, "No more connected devices");
finish();
}
}
abortBroadcast();
}
};
}
When I run this code, I get the following chain:
Start MainActivity (not included, it only contains an activity with the default main layout, so that the applications receiver is registered)
Switch on a bluetooth device (This has been paired earlier, so android knows about it)
Wait until it connects and get this:
DEVICE CONNECTED
onCreate
onResume
Switch off the bluetooth device and I then get this:
DEVICE DISCONNECTED
onDestroy
onCreate
onResume
I can't grasp why the activity is getting destroyed restarting at this point. The activity is already running, the BroadcastReceiver only sends a broadcast to an already running activity. I can't figure out why there's a reason for the Activity to kill itself and then restart again. This leaves me in a state of the Activity still running, but it is not the original Activity that was started.
I do however see something in the logcats that seem to have something to do with this, and it's in this sequencing;
06-02 15:45:09.156 26431 26431 D BT : DEVICE DISCONNECTED
06-02 15:45:09.213 19547 19547 D BluetoothAdapterService: handleMessage() - MESSAGE_PROFILE_CONNECTION_STATE_CHANGED
06-02 15:45:09.213 26431 26431 D BT : onDestroy
06-02 15:45:09.214 19547 19547 D BluetoothAdapterProperties: CONNECTION_STATE_CHANGE: FF:FF:20:00:C1:47: 2 -> 0
06-02 15:45:09.216 3502 3805 D CachedBluetoothDevice: onProfileStateChanged: profile HID newProfileState 0
06-02 15:45:09.237 414 414 W SurfaceFlinger: couldn't log to binary event log: overflow.
06-02 15:45:09.239 26431 26431 D BT : onCreate
06-02 15:45:09.243 26431 26431 D BT : onResume
In the AndroidManifest.xml add the following for the Activity, it is worked for me.
android:configChanges="keyboard|keyboardHidden"
Having read this https://developer.android.com/guide/components/broadcasts.html#effects_on_process_state I can probably safely conclude that the reason for why onDestroy gets called is because the receiver affects the process in which it is run, effectively meaning when the receiver has run its onReceive method, it will destroy itself and take the Activity with it.
I would of course have wished it was working differently, but I believe this is what effectively is going on and need to take another approach.
I know this answer is very late, but I was facing this issue with my activity tag. In Manifest file I have added below line for configChange.
android:configChanges="keyboard|orientation|screenSize|keyboardHidden|navigation|screenLayout"
Now my application does not kill itself.

Prevent a new Activity from spawning when a Bluetooth device connects

Goals
If a bluetooth device connects, and no Activity is running, start Activity
If a bluetooth device connects, and an Activity is already running, connect to the already running Activity
Problem
As soon as a device connects, a new Activity starts. I have not been able to make the app reuse the same Activity.
What I have managed to solve
If a bluetooth device connects, and no Activity is running, start Activity
The problem manifests itself in the use of BroadCastReceivers which in turn starts the Activity using intents. For some reason the Activity keep running through its lifecycle, spawning up new windows, when a new device connects.
I've tested this solely on a Nexus 6P with Android N. I have no idea yet what kind of implications this implementation means for any other devices yet. But I at least need to get this working on one device.
Manifest
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".BtActivity" />
<receiver android:name=".BtConnectionBroadcastReceiver" android:priority="100000">
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
<action android:name="android.intent.action.MEDIA_BUTTON" />
<action android:name="android.media.VOLUME_CHANGED_ACTION" />
</intent-filter>
</receiver>
</application>
BtConnectionBroadcastReceiver
public class BtConnectionBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "BT";
public static final String BROADCAST_ACTION_CONNECTED = "CONNECTED";
public static final String BROADCAST_ACTION_DISCONNECTED = "DISCONNECTED";
SharedPreferences mSharedPreferences;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
// Get the BluetoothDevice object from the Intent
Log.d(TAG, "DEVICE CONNECTED");
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d("DEVICE NAME", device.getName());
Log.d("DEVICE ADDRESS", device.getAddress());
Intent i = new Intent(context, BtActivity.class);
context.startActivity(i);
} else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
Log.d(TAG, "DEVICE DISCONNECTED");
intent = new Intent();
intent.setAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
context.sendBroadcast(intent);
}
}
BtActivity
public class BtActivity extends AppCompatActivity {
private static final String TAG = "BT";
Window mWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt);
Log.d(TAG, "onCreate");
IntentFilter filter = new IntentFilter(BtConnectionBroadcastReceiver.INTENT_FILTER);
filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_CONNECTED);
filter.addAction(BtConnectionBroadcastReceiver.BROADCAST_ACTION_DISCONNECTED);
//registerReceiver(mReceiver, filter);
mWindow = getWindow();
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
//params.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_OFF;
params.screenBrightness = 0.2f;
mWindow.setAttributes(params);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mWindow.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
mWindow.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_IMMERSIVE);
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy");
}
}
When I run this code, I get the following chain:
Start MainActivity (not included, it only contains an activity with the default main layout, so that the applications receiver is registered)
Switch on a bluetooth device (This has been paired earlier, so android knows about it)
Wait until it connects and get this:
DEVICE CONNECTED
onCreate
onResume
I can't grasp why the activity is restarting at this point. The activity is already running, the BroadcastReceiver only sends a broadcast to an already running activity. I can't figure out why there's a reason for the Activity to kill itself and then restart again.
Try by setting launch mode to the activity which is being started.
android:launchMode="singleTop"
This delivers the intent to the same activity instance if this activity is currently the top most activity in that task and onNewIntent() method of the activity will be invoked instead of onCreate(). And manage the functionality by passing intent extras. If this activity is not the top most activity in its task or if there is no activity running at all, then new instance of activity will be created and onCreate() followed by onResume() will be invoked.
Other launch modes like "singleTask"/"singleInstance" also can be used based on the need.
Hope this helps.
I had the same issue - something was calling onDestroy upon Bluetooth connection state changed (of the barcode scanner). I have fallowed author`s other post (as mentioned) and it was solved: https://stackoverflow.com/a/52165268/12762397
Posting this to speed up solution for someone else in the future.
It is necessary to add
<activity
...
android:configChanges="keyboard|keyboardHidden"/>
Works like a charm!

Running a receiver even if the app is not open

Well some months ago I learned the basics of android and now I'm triying to practice to remember what I learned. So the problem is that I'm doing an app that when it catches a change in the status of the screen (screen on/screen off) it does something. I want that when the app is not running (becausethe user killed it by pressing the home button or something like that) it still does what I want. I have decided to use receiver but I don't know if it's the correct option.
If the app is minimized it works but the problem whenthe user presses the "recent apps" button and slides the app. Then the receiver doesn't catch anything.
In the manifest I've declared:
<receiver android:name=".MyReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.SCREEN_OFF"/>
</intent-filter>
</receiver>
My main activity (maybe I have something wrong there):
public class MainActivity extends Activity {
private MyReceiver myReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);
}
#Override
protected void onDestroy() {
if (myReceiver != null) {
unregisterReceiver(myReceiver);
myReceiver = null;
}
super.onDestroy();
}
}
and my receiver:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("android.intent.action.SCREEN_OFF")) {
Log.e("In on receive", "In Method: ACTION_SCREEN_OFF");
Toast.makeText(context, "DO SOMETHING",Toast.LENGTH_LONG).show();
}
else if (action.equals("android.intent.action.SCREEN_ON")) {
Log.e("In on receive", "In Method: ACTION_SCREEN_ON");
Toast.makeText(context, "DO SOMETHING2",Toast.LENGTH_LONG).show();
}
}
}
Really appreciate if you could take a look :D.
Thank you
You have registered the receiver in the manifest. So don't register and unregister it in the MainActivity. That's the problem. So once the app is killed, onDestroy() gets called and your receiver is unregistered and will no longer listen.
Declaring the the receiver in the manifest means that your app will always listen to broadcasts. And that's exactly what you want. So remove the register/unregister part from the MainActivity.
UPDATE: It seems that SCREEN_ON and SCREEN_OFF can't be registered via the manifest. This might possibly be for a security reason. So in this case you have to register this via code. But the problem here is that, once you quit the app, onDestroy() is called and you are no longer listening. If you are app really need this feature, you have to create a service and have that run constantly in the the background. You can use that to listen to the broadcast.

part-1 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart

Status:--- I equally accept Karakuri's and Sharad Mhaske's answer, but since Sharad Mhaske answer after the start of bounty, the bounty should go to him.
Part-2 made: part-2 persistent foreGround android service that starts by UI, works at sleep mode too, also starts at phone restart
In stack overflow, only one answer may be accepted. I see both answers as acceptable but one has to be chosen (I chosed at random).
Viewers are invited to up/down vote answers/question to appreciate the effort!. I upvoted Karakuri's answer to compensate reputation.
Scenario:---
I want to make the user click a start/stop button and start/stop a service from UI activity. I have made the UI so dont care about that. But Just the logic of the Button click event.
Do not want the service to be bound to the UI activity. If activity closes, the service should keep running.
Want to make most effort that the service be persistent and does not stops in any case. Will give it most weight and run it as ForGroundSerice as it has a higher hierarchy of importance. (hope that's ok?)
Unless the stop button is clicked by my apps UI, do not want it to be stopped (or should restart itself) Even if android reclaim memory. I and the user of the phone, both are/will be aware of it. The service is most of importance. Even at sleep.
details= my app do some operations, sleep for user provided time (15 minuts usually), wakes and perform operations again. this never ends)
If I need AlarmManager, How to implement that? or any other way? Or just put the operations in a neverending while loop and sleep for 15 minuts at the end?
When the service is started (by clicked on start button). It should make an entry so that it auto starts if phone restarts.
QUESTION:---
Primary Question:
Just can't get an optimal strategy for the scenario... and also stuck on small bits of code, which one to use and how.
Gathered bits and pieces from stackoverflow.com questions, developer.android.com and some google results but cannot implement in integration.
Please read out the Requests Section.
Secondary Question:
The comments in my code are those small questions.
Research and Code:---
Strategy:
want this to happen every time the user opens the UI.
//Start Button:-----
//check if ForGroundService is running or not. if not running, make var/settings/etc "serviceStatus" as false
<-------(how and where to stare this and below stated boolean?)
//start ForGroundService
<-------(how?)
//make "SericeStatus" as true
//check if "ServiceStartOnBoot" is false
//Put ForGroundService to start on boot -------(to make it start when ever the phone reboots/restarts)
<-------(how?)
//make "ServiceStartOnBoot" as true
// the boolean can also be used to check the service status.
//Stop Button:------
//makes SericeStatus and ServiceStartOnBoot as false
//stops service and deletes the on boot entry/strategy
Activity UI class that starts/stops the service:
public class SettingsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
//some button here to start / stop and their onClick Listners
Intent mySericeIntent = new Intent(this, TheService.class);
}
private void startMyForGroundService(){
startService(mySericeIntent);
}
private void stopMyForGroundSerice(){
stopService(mySericeIntent);
/////// is this a better approach?. stopService(new Intent(this, TheService.class));
/////// or making Intent mySericeIntent = new Intent(this, TheService.class);
/////// and making start and stop methods use the same?
/////// how to call stopSelf() here? or any where else? whats the best way?
}
}
The Service class:
public class TheService extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startForeground(1, new Notification());
////// will do all my stuff here on in the method onStart() or onCreat()?
return START_STICKY; ///// which return is better to keep the service running untill explicitly killed. contrary to system kill.
///// http://developer.android.com/reference/android/app/Service.html#START_FLAG_REDELIVERY
//notes:-// if you implement onStartCommand() to schedule work to be done asynchronously or in another thread,
//then you may want to use START_FLAG_REDELIVERY to have the system re-deliver an Intent for you so that it does not get lost if your service is killed while processing it
}
#Override
public void onDestroy() {
stop();
}
public void stop(){
//if running
// stop
// make vars as false
// do some stopping stuff
stopForeground(true);
/////// how to call stopSelf() here? or any where else? whats the best way?
}
}
The Menifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.myapp.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myapp.SettingsActivity"
android:label="#string/title_activity_settings" >
</activity>
</application>
</manifest>
References:---
Android - implementing startForeground for a service? pointing answer 1, example code.
Trying to start a service on boot on Android
Android: Start Service on boot?
http://developer.android.com/guide/components/services.html
http://developer.android.com/reference/android/app/Service.html
http://developer.android.com/training/run-background-service/create-service.html not preffered by me.
http://developer.android.com/guide/components/processes-and-threads.html my starting point of research
Requests:---
I think this question is a normal practice for most people who are dealing with services.
In that vision, please only answer if you have experience in the scenario and can comprehensively explain the aspects and strategy with maximum sample code as a complete version so it would be a help to the community as well.
Vote up and down (with responsibility) to the answers as it matters to me who shared their views, time and experience and helped me and the community.
Que:Want to make most effort that the service be persistent and does not stops in any case. Will give it most weight and run it as ForGroundSerice as it has a higher hierarchy of importance. (hope that's ok?)
Answer:you need to start service with using START_STICKY Intent flag.
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
Que:If I need AlarmManager, How to implement that? or any other way? Or just put the operations in a neverending while loop and sleep for 15 minuts at the end?
Answer:you need to register alarmmanager within service for the time after to some task.
//register alarm manager within service.
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent("com.xxxxx.tq.TQServiceManager"), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 , 30 * 1000 , pendingIntent);
//now have a broadcastreceiver to receive this intent.
class Alarmreceiver extends Broadcastreceiver
{
//u can to task in onreceive method of receiver.
}
//register this class in manifest for alarm receiver action.
Que:When the service is started (by clicked on start button). It should make an entry so that it auto starts if phone restarts.
Answer:use broadcast reciver to listen for onboot completed intent.
public class StartAtBootServiceReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
try {
if( "android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
ComponentName comp = new ComponentName(context.getPackageName(), LicensingService.class.getName());
ComponentName service = context.startService(new Intent().setComponent(comp));
if (null == service){
// something really wrong here
//Log.Write("Could not start service " + comp.toString(),Log._LogLevel.NORAML);
}
}
else {
//Log.Write("Received unexpected intent " + intent.toString(),Log._LogLevel.NORAML);
}
} catch (Exception e) {
//Log.Write("Unexpected error occured in Licensing Server:" + e.toString(),Log._LogLevel.NORAML);
}
}
}
//need to register this receiver for Action_BOOTCOMPLETED intent in manifest.xml file
Hope this helps you clear out things :)
If you start a service with startService(), it will keep running even when the Activity closes. It will only be stopped when you call stopService(), or if it ever calls stopSelf() (or if the system kills your process to reclaim memory).
To start the service on boot, make a BroadcastReceiver that just starts the service:
public class MyReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
Then add these to your manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application ... >
<receiver android:name="MyReceiver"
android:enabled="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
Notice that the receiver is not enabled at first. When the user starts your service, use PackageManager to enable the receiver. When the user stops your service, use PackageManager to disable the receiver. In your Activity:
PackageManager pm = getPackageManager();
ComponentName receiver = new ComponentName(this, MyReceiver.class);
pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Use same method with PackageManager.COMPONENT_ENABLED_STATE_DISABLED to disable it.
I have made something like this myself but I learned a lot while developing it and discovered it is not completely necesary to have the service running all day draining your battery. what I made is the following:
Implement a Service that reacts to events. In my particular I wanted to automate my Wifi and mobile data connection. so i react to events like wifi connecting and disconnecting, screen turning on and off, etc. So this service executes what ever needs to be executed responding to this event and then stops, scheduling any further actions with the AlarmManager if so needed.
now, this events can by timers like you said yourself every 15 minutes it does something and sleeps, that sounds to me that you really dont want the service running 24/7 but just executing something every 15 minutes. that is perfectly achievable with the AlarmManager without keeping your service running forever.
I recommend implementing this service deriving from commonsware's WakefulIntentService.
This class already handles the wakeLock for you so that you can exceute code even if phone is asleep. it will simply wakeup execute and go back to sleep.
Now. About your question regarding the activity starting and stoping the service. you can implement in the button that it starts or cancels the AlarmManager alarm. Also you can use the sharedPreferences to store a simple boolean that tells you if it is enabled or not so the next time your service runs it can read the value and know if it should continue or stop.
If you implement it as a event-reactive service as i said, your button can even react to broadcast intents so that your activity doesn't even have to call the service directly just broadcast an intent and the service can pick it like other events. use a BroadcastReceiver for this.
I'll try to give examples but be wary that what you're asking is a lot of code to put it in one place...
BootReceiver:
public class BootReceiver extends BroadcastReceiver
{
private static final String TAG = BootReceiver.class.getSimpleName();
#Override
public void onReceive(final Context context, final Intent intent)
{
final Intent in = new Intent(context, ActionHandlerService.class);
in.setAction(Actions.BOOT_RECEIVER_ACTION); //start the service with a flag telling the event that triggered
Log.i(TAG, "Boot completed. Starting service.");
WakedIntentService.sendWakefulWork(context, in);
}
}
Service:
public class ActionHandlerService extends WakedIntentService
{
private enum Action
{
WIFI_PULSE_ON, WIFI_PULSE_OFF, DATA_PULSE_ON, DATA_PULSE_OFF, SCREEN_ON, SCREEN_OFF, WIFI_CONNECTS, WIFI_DISCONNECTS, WIFI_CONNECT_TIMEOUT, WIFI_RECONNECT_TIMEOUT, START_UP, BOOT_UP
}
public ActionHandlerService()
{
super(ActionHandlerService.class.getName());
}
#Override
public void run(final Intent intent)
{
mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mSettingsContainer.enabled = mSettings.getBoolean(getString(R.string.EnabledParameter), false);
if (intent != null)
{
final String action = intent.getAction();
if (action != null)
{
Log.i(TAG, "received action: " + action);
if (action.compareTo(Constants.Actions.SOME_EVENT) == 0)
{
//Do what ever you want
}
else
{
Log.w(TAG, "Unexpected action received: " + action);
}
}
else
{
Log.w(TAG, "Received null action!");
}
}
else
{
Log.w(TAG, "Received null intent!");
}
}
}
And your Manifest could go something like this:
<?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.yourcompany.yourapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="false"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.yourcompany.yourapp.activities.HomeActivity"
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:name="com.yourcompany.yourapp.services.ActionHandlerService" />
<receiver android:name="com.yourcompany.yourapp.receivers.BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
</application>
</manifest>

In Android how do you register to receive headset plug broadcasts?

I am working in Android 2.1, and I want to detect when the headset is plugged in/taken out. I'm pretty new to android.
I think the way to do it is using a Broadcast receiver. I sublcassed this, and I also put the following in my AndroidManifest.xml. But do you have to register the receiver somehwere else, like in the activity? I'm aware there are lots of threads on this, but I don't really understand what they're talking about. Also, what's the difference between registering in AndroidManifest.xml versus registering dynamically in your activity?
<receiver android:enabled="true" android:name="AudioJackReceiver" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" >
</action>
</intent-filter>
</receiver>
And this was the implementation of the class (plus imports)
public class AudioJackReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.w("DEBUG", "headset state received");
}
}
I was just trying to see if it works, but nothing shows up when I unplug/plug in the headset while running the application.
EDIT: the documentation doesn't say this, but is it possible that this one won't work if registered in the manifest? I was able to get it to respond when I registered the receiver in one of my applications (or do you have to do that anyway?)
Just complementing Greg`s answer, here is the code that you need divided in two parts
Register the Service in the first Activity (here its called MainActivity.java).
Switch over the result of the ACTION_HEADSET_PLUG action in the BroadCastReceiver.
Here it goes:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private MusicIntentReceiver myReceiver;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver = new MusicIntentReceiver();
}
#Override public void onResume() {
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
registerReceiver(myReceiver, filter);
super.onResume();
}
private class MusicIntentReceiver extends BroadcastReceiver {
#Override public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
switch (state) {
case 0:
Log.d(TAG, "Headset is unplugged");
break;
case 1:
Log.d(TAG, "Headset is plugged");
break;
default:
Log.d(TAG, "I have no idea what the headset state is");
}
}
}
}
Here are two sites that may help explain it in more detail:
http://www.grokkingandroid.com/android-tutorial-broadcastreceiver/
http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html
You have to define your intent; otherwise it won't access the system function. The broadcast receiver; will alert your application of changes that you'd like to listen for.
Every receiver needs to be subclassed; it must include a onReceive(). To implement the onReceive() you'll need to create a method that will include two items: Context & Intent.
More then likely a service would be ideal; but you'll create a service and define your context through it. In the context; you'll define your intent.
An example:
context.startService
(new Intent(context, YourService.class));
Very basic example. However; your particular goal is to utilize a system-wide broadcast. You want your application to be notified of Intent.ACTION_HEADSET_PLUG.
How to subscribe through manifest:
<receiver
android:name="AudioJackReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>
Or you can simply define through your application; but. Your particular request; will require user permissions if you intend to detect Bluetooth MODIFY_AUDIO_SETTINGS.
You need to enable the broadcast receiver and set the exported attribute to true:
<receiver
android:name="AudioJackReceiver"
android:enabled="true"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG" />
</intent-filter>
</receiver>

Categories

Resources