java 杀死android应用进程,Android:当应用被杀死时,保持服务运行

所有答案似乎都是正确的,因此我将在此处给出完整答案。

首先,做您想做的事的最简单方法是,当应用程序被手动终止时,在Android中启动广播,并定义一个自定义设置,以在此之后触发服务重启。BroadcastReceiver

现在,让我们进入代码。

在以下位置创建您的服务 YourService.java

请注意该onCreate()方法,其中对于不同于Android Oreo的 Build版本,我们将以不同的方式启动前台服务。这是因为最近引入了严格的通知策略,我们必须定义自己的通知通道以正确显示它们。

方法中的this.sendBroadcast(broadcastIntent);in onDestroy()是一条语句,它以动作名称异步发送广播"restartservice"。稍后我们将以此为触发来重新启动我们的服务。

在这里,我们定义了一个简单的Timer任务,该任务每1秒打印一次计数器值,Log而每次打印时都会递增一次。

public class YourService extends Service {

public int counter=0;

@Override

public void onCreate() {

super.onCreate();

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)

startMyOwnForeground();

else

startForeground(1, new Notification());

}

@RequiresApi(Build.VERSION_CODES.O)

private void startMyOwnForeground()

{

String NOTIFICATION_CHANNEL_ID = "example.permanence";

String channelName = "Background Service";

NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);

chan.setLightColor(Color.BLUE);

chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

assert manager != null;

manager.createNotificationChannel(chan);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

Notification notification = notificationBuilder.setOngoing(true)

.setContentTitle("App is running in background")

.setPriority(NotificationManager.IMPORTANCE_MIN)

.setCategory(Notification.CATEGORY_SERVICE)

.build();

startForeground(2, notification);

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

super.onStartCommand(intent, flags, startId);

startTimer();

return START_STICKY;

}

@Override

public void onDestroy() {

super.onDestroy();

stoptimertask();

Intent broadcastIntent = new Intent();

broadcastIntent.setAction("restartservice");

broadcastIntent.setClass(this, Restarter.class);

this.sendBroadcast(broadcastIntent);

}

private Timer timer;

private TimerTask timerTask;

public void startTimer() {

timer = new Timer();

timerTask = new TimerTask() {

public void run() {

Log.i("Count", "=========  "+ (counter++));

}

};

timer.schedule(timerTask, 1000, 1000); //

}

public void stoptimertask() {

if (timer != null) {

timer.cancel();

timer = null;

}

}

@Nullable

@Override

public IBinder onBind(Intent intent) {

return null;

}

}

创建一个广播接收器以响应您在中自定义的广播 Restarter.java

现在应该使用"restartservice"您刚刚在其中定义的操作名称进行广播,YourService.java以触发将重新启动服务的方法。这是BroadcastReceiver在Android中使用完成的。

我们将覆盖内置onRecieve()方法,BroadcastReceiver以添加将重新启动服务的语句。该功能startService()将无法在Android Oreo 8.1及更高版本中正常运行,因为严格的后台策略将在应用终止后重启后立即终止服务。因此,我们将startForegroundService()用作更高版本,并显示连续的通知以保持服务运行。

public class Restarter extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

Log.i("Broadcast Listened", "Service tried to stop");

Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

context.startForegroundService(new Intent(context, YourService.class));

} else {

context.startService(new Intent(context, YourService.class));

}

}

}

定义您MainActivity.java在应用启动时调用服务。

在这里,我们定义了一个单独的isMyServiceRunning()方法来检查后台服务的当前状态。如果该服务未运行,请使用启动它startService()。

由于该应用程序已经在前台运行,因此我们无需将该服务作为前台服务启动以防止自身终止。

请注意,在其中onDestroy()我们专门调用stopService(),以便调用我们的重写方法。如果不这样做,则该服务将在应用被终止后自动终止,而无需调用我们修改过的onDestroy()方法YourService.java

public class MainActivity extends AppCompatActivity {

Intent mServiceIntent;

private YourService mYourService;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mYourService = new YourService();

mServiceIntent = new Intent(this, mYourService.getClass());

if (!isMyServiceRunning(mYourService.getClass())) {

startService(mServiceIntent);

}

}

private boolean isMyServiceRunning(Class> serviceClass) {

ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {

if (serviceClass.getName().equals(service.service.getClassName())) {

Log.i ("Service status", "Running");

return true;

}

}

Log.i ("Service status", "Not running");

return false;

}

@Override

protected void onDestroy() {

stopService(mServiceIntent);

super.onDestroy();

}

}

最后将它们注册到您的 AndroidManifest.xml

以上三个类别均需在中单独注册AndroidManifest.xml。

请注意,我们定义intent-filter的动作名称为"restartservice",将Restarter.java其注册为receiver。这样可以确保BroadcastReciever在系统遇到具有给定操作名称的广播时调用我们的自定义。

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme">

android:name="Restarter"

android:enabled="true"

android:exported="true">

android:name="YourService"

android:enabled="true" >

现在,如果应用程序已从任务管理器中终止,这应该再次重新启动您的服务。只要用户未Force Stop从“ 应用程序设置”中选择该应用程序,该服务就会在后台继续运行。

UPDATE:荣誉对Dr.jacky指点出来。上面提到的方法仅在onDestroy()调用服务的时才有效,在某些时候这种情况可能并非如此,而我没有意识到。谢谢。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值