我已经实现了一项Android服务(START_STICKY
),该服务在设备启动时启动并在后台运行。该服务的功能是与SD卡交互。由于它连续运行,从粘性开始消耗电池。为了解决电池消耗大的问题,我想在用户使用设备时启动此服务。
理想情况下,根据ACTION_SCREEN_ON
& ACTION_SCREEN_OFF
意图。
当我测试时发现我无法注册ACTION_SCREEN_OFF
&清单中的ACTION_SCREEN_ON
,因此我在我的服务中创建了一个广播接收器来捕获ACTION_SCREEN_OFF
& ACTION_SCREEN_ON
。
但是,因为当我在ACTION_SCREEN_OFF
停止服务时,我无法注册清单中的意图。如何在屏幕重新启动时启动它?
注意:
正如我已经提到的,SCREEN_ON
+ SCREEN_OFF
无法在清单文件中注册。它注册为
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
broadcastReceiver = new TestReceiver();
registerReceiver(broadcastReceiver, filter);
因此,当服务未运行时,此意图不会触发。
答案 0 :(得分:1)
您可以使用BroadCastReceiver根据广播类型调用您的服务
public class MyReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
}
else if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
// and do whatever you need to do here
}
}
答案 1 :(得分:0)
为ACTION_SCREEN_ON,ACTION_SCREEN_OFF和ACTION_USER_PRESENT设置广播接收器。
触发ACTION_SCREEN_ON时,将调用onResume活动。创建一个处理程序并等待ACTION_USER_PRESENT。触发后,实施您想要的活动。
如下注册接收器:
private void registBroadcastReceiver() {
final IntentFilter theFilter = new IntentFilter();
/** System Defined Broadcast */
theFilter.addAction(Intent.ACTION_SCREEN_ON);
theFilter.addAction(Intent.ACTION_SCREEN_OFF);
mPowerKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String strAction = intent.getAction();
if (strAction.equals(Intent.ACTION_SCREEN_OFF) || strAction.equals(Intent.ACTION_SCREEN_ON)) {
// > Your playground~!
}
}
};
getApplicationContext().registerReceiver(mPowerKeyReceiver, theFilter);
}