【发布时间】:2014-07-19 13:22:58
【问题描述】:
如何写一个service,当device boots时自动启动?例如:当我启动手机时,我收到了新的WhatsApp 消息,而之前没有打开WhatsApp。
【问题讨论】:
如何写一个service,当device boots时自动启动?例如:当我启动手机时,我收到了新的WhatsApp 消息,而之前没有打开WhatsApp。
【问题讨论】:
Himanshu 回答的两个补充:
启动监听应用程序不得安装在 sdcard 上。请记住,设备启动可能已完成 在 sdcard 甚至挂载之前导致您的应用程序的启动侦听器没有被激活
只有在用户激活您的 应用第一次。从 4.2 开始(此处不确定)android 会阻止所有服务 & 新安装的应用声明的监听器从被激活直到被用户显式激活。
在用户单击主屏幕图标时显式激活。
【讨论】:
您可以使用它来使其工作:
您的manifest 文件:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.jjoe64">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application>
<receiver android:name=".BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".BackgroundService" />
</application>
</manifest>
添加这个类BootCompletedIntentReceiver.java
public class BootCompletedIntentReceiver extends BroadcastReceiver {
@Override
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);
}
}
}
这将使它在设备启动后自动启动您的服务
【讨论】:
BroadcastReceiver 中的Intent?为什么不用对应的常量Intent.ACTION_BOOT_COMPLETED?还要用 4 个空格来缩进你的代码,而不是一个......这次我已经修复了你的格式。