如何在设备启动时启动服务(自动运行应用程序等)
首先:从 Android 3.1+ 版本开始,如果用户从未启动过您的应用程序至少一次或用户“强制关闭”应用程序,您不会收到 BOOT_COMPLETE。这样做是为了防止恶意软件自动注册服务。此安全漏洞已在较新版本的 Android 中关闭。
解决方案:
使用活动创建应用程序。当用户运行它一次应用程序可以接收 BOOT_COMPLETE 广播消息。
第二:在挂载外部存储之前发送 BOOT_COMPLETE。如果应用程序安装到外部存储,它将不会收到 BOOT_COMPLETE 广播消息。
在这种情况下,有两种解决方案:
- 将您的应用安装到内部存储
- 在内部存储中安装另一个小应用程序。此应用程序接收 BOOT_COMPLETE 并在外部存储上运行第二个应用程序。
如果您的应用程序已经安装在内部存储中,那么下面的代码可以帮助您了解如何在设备启动时启动服务。
在 Manifest.xml 中
允许:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
注册您的 BOOT_COMPLETED 接收器:
<receiver android:name="org.yourapp.OnBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
注册您的服务:
<service android:name="org.yourapp.YourCoolService" />
在接收器 OnBoot.java 中:
public class OnBoot extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
// Create Intent
Intent serviceIntent = new Intent(context, YourCoolService.class);
// Start service
context.startService(serviceIntent);
}
}
对于 HTC,如果设备未捕获 RECEIVE_BOOT_COMPLETED,您可能还需要在清单中添加此代码:
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
接收器现在看起来像这样:
<receiver android:name="org.yourapp.OnBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
如何在不重启模拟器或真实设备的情况下测试 BOOT_COMPLETED?这很简单。尝试这个:
adb -s device-or-emulator-id shell am broadcast -a android.intent.action.BOOT_COMPLETED
如何获取设备ID?获取具有 id 的已连接设备列表:
adb devices
默认情况下,ADT 中的 adb 可以在以下位置找到:
adt-installation-dir/sdk/platform-tools
享受!)