Android:如何检测手机何时处于活动状态和空闲状态? [英] Android: How to detect when phone is active and idle?
本文介绍了Android:如何检测手机何时处于活动状态和空闲状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个知道用户何时使用电话的应用程序(启动屏幕并关闭屏幕)。一段时间后,我需要调用 doSomething()
方法。
I want to create an app that will know when user is using the phone(start the screen and close the screen). After a period of time I need to call doSomething()
method.
问题:
1。如何知道用户何时开始使用手机以及何时关闭屏幕?
1.How can I know when user start using the phone and when he close the screen?
2.我应该使用Service还是IntentService?对于我来说,哪个更好?
2.Should I use Service or IntentService? Which is better in my case?
推荐答案
您可以使用BroadcastReceiver和Service尝试这样的事情:
You can try something like this using a BroadcastReceiver and a Service:
使用BroadcastReceiver的课程:
Your class using The BroadcastReceiver:
public class ScreenReceiver extends BroadcastReceiver {
private boolean screenOff;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
服务:
public static class ScreenService extends Service {
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
@Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
//Implement here your code
} else {
//Implement here your code
}
}
}
这篇关于Android:如何检测手机何时处于活动状态和空闲状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文