public class BootCompletedIntentReceiver扩展BroadcastReceiver { @覆盖 public void onReceive(Context context,Intent intent){ if(“android.intent.action.BOOT_COMPLETED”.equals(intent.getAction())){ Intent pushIntent = new Intent(context,BackgroundService.class); context.startService(pushIntent); } } }
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);
// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
然后,在您的服务中,确保释放唤醒锁:
@Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us. We can do whatever we need to here and then tell it that
// it can release the wakelock.
...
Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
8 回答
你应该注册BOOT_COMPLETE以及REBOOT
创建BroadcastReceiver并将其注册为接收ACTION_BOOT_COMPLETED . 您还需要RECEIVE_BOOT_COMPLETED权限 .
阅读:Listening For and Broadcasting Global Messages, and Setting Alarms
你的接收者:
你的AndroidManifest.xml:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import com.jjoe64.BackgroundService;
public class BootCompletedIntentReceiver扩展BroadcastReceiver {
@覆盖
public void onReceive(Context context,Intent intent){
if(“android.intent.action.BOOT_COMPLETED”.equals(intent.getAction())){
Intent pushIntent = new Intent(context,BackgroundService.class);
context.startService(pushIntent);
}
}
}
来自http://www.jjoe64.com/2011/06/autostart-service-on-device-boot.html
这里发布的大多数解决方案都缺少一个重要的部分:在没有唤醒锁定的情况下执行它会导致服务在完成处理之前被杀死的风险 . 在另一个线程中看到这个解决方案,也在这里回答 .
由于在api 26中不推荐使用WakefulBroadcastReceiver,因此建议 for API Levels below 26
您需要获得唤醒锁定 . 幸运的是,Support library gives us a class这样做:
然后,在您的服务中,确保释放唤醒锁:
不要忘记添加WAKE_LOCK权限并在清单中注册您的接收者:
还要在Manifest中注册您创建的服务,并使用-enate权限
然后在braod cast Reciever中打电话给你的服务
首先在manifest.xml文件中注册一个接收器:
然后为这个接收器写一个广播,如:
Pls check JobScheduler for apis above 26
WakeLock 是最好的选择,但如果你认为api水平高于26,那么它是 deprecated in api level 26 请检查this link
https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html#startWakefulService(android.content.Context,%20android.content.Intent)
它说
所以它说cosider JobScheduler
https://developer.android.com/reference/android/app/job/JobScheduler
如果要做某事而不是开始并保留它,你可以收到广播ACTION_BOOT_COMPLETED
如果不是关于前台请检查辅助功能服务是否可以
另一个选择是从广播接收器启动一个活动,并在onCreate()内启动服务后完成它,因为较新的Android版本不允许从接收器启动服务