将(已启动)添加Service
到您的应用程序。即使用户退出了您的应用程序,该服务仍将在后台运行。
此外,您可以实现一个 BroadcastReceiver 来监听手机的 Intent 并让您的服务在手机启动时启动!
我的服务.java
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId){
// START YOUR TASKS
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// STOP YOUR TASKS
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent){
return null;
}
BootReceiver.java
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent("your.package.MyService");
context.startService(serviceIntent);
}
}
}
}
AndroidManifest.xml
// 在清单标签中
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
// 在您的应用程序标签中
<service android:name=".MyService">
<intent-filter>
<action android:name="your.package.MyService" />
</intent-filter>
</service>
<receiver
android:name=".BootReceiver"
android:enabled="true"
android:exported="true"
android:label="BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
如果你想从一个活动开始你的服务,只需使用
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
if (!isMyServiceRunning()){
Intent serviceIntent = new Intent("your.package.MyService");
context.startService(serviceIntent);
}