I'm developing an application where I need to pause an activity when screen is off and when screen is on, it must be resumed.
I want the detection to be done inside the service. I have used startservice() to start up my service. But don't know where to put the following code:
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (pm.isScreenOn())
MyActivity.onResume();
else
MyActivity.onPause();
I tried googling around but I couldn't find it.
Use a BroadcastReceiver. Declare it in the service:
private final BroadcastReceiver myReceiver = new myReceiver();
In your service onCreate:
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(myReceiver, filter);
In your service onDestroy:
unregisterReceiver(myReceiver);
Create the receiver:
public class myReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//Do something when the screen goes off
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
//Do something when it's back on
}
}
Anyway, keep in mind that the activities by default goes onPause and back onResume when the screen goes off/on
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.