android - starting background service while phone turn on with example code
问题描述
I need an app which will run always in the background and apps will start while phone is turn on. Please help me with example code. I already tried several code but it run on background while pressing button after start the apps
解决方案
您需要接听BOOT_COMPLETED
电话,然后启动服务。请按照以下步骤操作
第 1 步:创建您的服务
public class myService extends Service{
public myService(){}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
}
第 2 步:创建引导接收器
public class BootReceiver extends BroadcastReceiver {
public void onReceive(final Context context, Intent intent) {
Intent i = new Intent(context, RemindersService.class);
context.startService(i);
}
}
第 3 步:将它们添加到应用程序内的清单
<service
android:name=".services.RemindersService"
android:enabled="true"
android:exported="true" />
<receiver
android:name=".services.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
第 4 步:在清单中添加权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
而已。快乐编码。请注意,在 android Oreo 中,您需要将服务作为前台启动
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(i);
}
推荐阅读
- wpf - 如何在 GMap.NET 中使用 NetTopologySuite 的 R-Tree 显示丰富的标记 WPF
- javascript - 使用页面上的添加按钮在 codeigniter 中添加另一个 ckeditor
- vue.js - 尝试编辑使用 vue 编写的其他人的代码:{{ }} 小胡子内的属性值在哪里?
- c++ - STL 容器如何跟踪容器的当前大小超过总大小?
- javascript - 当我使用 Javascript 添加新的 CSS 样式时,那里的 JS 停止工作
- java - J内部框架组件未初始化
- java - 如何在 android 中为 textview/edittext 添加星号红色标记,使其成为必填字段?
- python-3.x - 在 deeplab 中运行测试文本“local_test.sh”时出现问题。但 modle_test.py 工作正常
- r - r中的ggplot中的双y轴(条形和线形)
- c# - 事件选项卡未显示在诊断工具 VS 2017 中