Android: 如何检测phone 处于活动状态和空闲状态?
Android: How to detect when phone is active and idle?
我想创建一个应用程序,它会知道用户何时使用 phone(启动屏幕和关闭屏幕)。一段时间后我需要调用 doSomething()
方法。
问题:
1.How 我可以知道用户何时开始使用 phone 以及何时关闭屏幕吗?
2.Should我用Service还是IntentService?我的情况哪个更好?
您可以使用 BroadcastReceiver 和服务来尝试这样的事情:
您的 class 使用 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
}
}
}
我想创建一个应用程序,它会知道用户何时使用 phone(启动屏幕和关闭屏幕)。一段时间后我需要调用 doSomething()
方法。
问题:
1.How 我可以知道用户何时开始使用 phone 以及何时关闭屏幕吗?
2.Should我用Service还是IntentService?我的情况哪个更好?
您可以使用 BroadcastReceiver 和服务来尝试这样的事情:
您的 class 使用 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
}
}
}