我需要在我的应用程序中提供一项服务,该服务可以在第一次启动并永远运行,即使用户重新启动他的手机,我的服务也会自动启动而无需运行我的应用程序。我写了这段代码,但是当用户重启他的手机时,我的服务没有再次启动!!
public class notifService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStart(intent, startId);
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
在主要 Activity 中,我开始这样的服务:
// start service
Intent service = new Intent(MainActivity.this, notifService.class);
MainActivity.this.startService(service);
谢谢你的帮助。
最佳答案
在 BroadcastReceiver 中监听 android.intent.action.BOOT_COMPLETED
并启动您的服务。
例如
public class YourDefinedBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, notifService.class);
context.startService(service);
}
}
此外,您必须持有权限:
引用:Automatically starting Services in Android after booting和 Android Start Service on Boot Automatically
关于java - 安排Android服务在手机重启后重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16644125/