使用<
action android:name =“android.intent.action.BOOT_COMPLETED”/>在设备开启时启动服务.
在AndroidManifest.xml中:
在AndroidManifest.xml中添加权限:
在代码部分BootBroadcastReceiver中:
public class BootBroadcastReceiver extends BroadcastReceiver {
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
// BOOT_COMPLETED” start Service
if (intent.getAction().equals(ACTION)) {
//Service
Intent serviceIntent = new Intent(context, StartOnBootService.class);
context.startService(serviceIntent);
}
}
}
编辑:如果您正在谈论设备屏幕开/关,那么您需要注册和用户出现或屏幕打开时启动服务.