您需要将您的应用程序变成一个服务。以下是Android关于创建服务组件的方式:
http://developer.android.com/guide/components/services.html
在MobiWare上也找到了这个:
如果您想追踪移动设备的使用情况或收集一些用户不知道的数据,这可能会对您有所帮助。
步骤1:创建一个没有图标的应用程序。通常,在清单中声明一个活动如下所示。
<activity
android:label="@string/app_name"
android:name="org.security.tracker.Tracker-activity" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
去掉分类标签,就不会再得到应用图标。
现在,您不需要活动了。因此,请删除此部分。
但是您可能会想,没有任何触发器该应用程序如何运行或者应用程序的起点是什么。
这就是解决方案。
<!-- Start the Service if applicable on boot -->
<receiver android:name="org.security.tracker.ServiceStarter" >
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
这将触发您在 Receiver 中编写的代码,从而可以运行服务来实现您的想法。
<service android:name="org.security.tracker.serviceCode" />
你需要添加这个权限。
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
你的代码仅在手机重启时运行。
第二步:编写你的代码
当手机重启时,广播接收器会被触发,然后你可以启动你的服务。
class ServiceStarter extends BroadcastReceiver {
@Override
public void onReceive(Context _context, Intent _intent) {
Intent i = new Intent("com.prac.test.MyPersistingService");
i.setClass(_context, ServiceCode.class);
_context.startService(i);
}
}