简体   繁体   English

即使应用程序被强制停止,也要重新启动服务,即使关闭应用程序,也要在后台继续运行服务如何?

[英]Restart the service even if app is force-stopped and Keep running service in background even after closing the app How?

I am trying to run a service in the background.我正在尝试在后台运行服务。 What my app does is when user checks checkbox then service starts and when it is unchecked service is stopped.我的应用程序所做的是当用户选中复选框然后服务启动时,当它被取消选中时服务停止。 Which is working perfectly fine.哪个工作得很好。 But the problem is when I closed the app from task manager it then also stops the service.但问题是当我从任务管理器关闭应用程序时,它也会停止服务。 What I want is to keep the service running even after it is close from task manager.我想要的是即使在从任务管理器关闭后也能保持服务运行。

This question has already been asked, look here .这个问题已经有人问过了,看这里 I will copy the accepted answere:我将复制接受的答案:

Here is an example of foreground service that I use and that works, it remains active when the app is closed.这是我使用的一个前台服务示例,该服务有效,当应用程序关闭时它保持活动状态。 Of course, it also must be started, and for that task the app must be running at a first glance, or a receiver of a boot event must be set, but this is another story.当然,它也必须启动,并且对于该任务,应用程序必须在第一眼中运行,或者必须设置启动事件的接收器,但这是另一回事。

public class MyService extends Service {
static final int NOTIFICATION_ID = 543;

public static boolean isServiceRunning = false;

@Override
public void onCreate() {
    super.onCreate();
    startServiceWithNotification();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction().equals(C.ACTION_START_SERVICE)) {
        startServiceWithNotification();
    }
    else stopMyService();
    return START_STICKY;
}

// In case the service is deleted or crashes some how
@Override
public void onDestroy() {
    isServiceRunning = false;
    super.onDestroy();
}

@Override
public IBinder onBind(Intent intent) {
    // Used only in case of bound services.
    return null;
}


void startServiceWithNotification() {
    if (isServiceRunning) return;
    isServiceRunning = true;

    Intent notificationIntent = new Intent(getApplicationContext(), MyActivity.class);
    notificationIntent.setAction(C.ACTION_MAIN);  // A string containing the action name
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent contentPendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.my_icon);

    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.app_name))
            .setTicker(getResources().getString(R.string.app_name))
            .setContentText(getResources().getString(R.string.my_string))
            .setSmallIcon(R.drawable.my_icon)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false))
            .setContentIntent(contentPendingIntent)
            .setOngoing(true)
//                .setDeleteIntent(contentPendingIntent)  // if needed
            .build();
    notification.flags = notification.flags | Notification.FLAG_NO_CLEAR;     // NO_CLEAR makes the notification stay when the user performs a "delete all" command
    startForeground(NOTIFICATION_ID, notification);
}

void stopMyService() {
    stopForeground(true);
    stopSelf();
    isServiceRunning = false;
}
}

Then I run it with然后我运行它

Intent startIntent = new Intent(getApplicationContext(), MyService.class);
startIntent.setAction(C.ACTION_START_SERVICE);
startService(startIntent);

Please note the two constants used as Actions, these are Strings that must start with the package name.请注意用作操作的两个常量,它们是必须以包名称开头的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM