我的 Android 服务无法继续运行

my Android service won't keep running

我有一个执行 AsyncTask 的服务,它在每次完成后调用自身。正如您将在下面看到的,我正在前台启动我的服务。当我将它插入我的计算机并将输出输出到 LogCat 时,它成功启动并保持按预期运行。我知道这是因为要进行测试,我的 AsyncTask 循环每 5 分钟发出一次通知。但是,当我从计算机上拔下它时,通知不会出现!就好像我启动后服务就完全停止了一样!

注意:我的服务是常规服务,不是 IntentService。

这是我的 onStartCommand...

@SuppressWarnings("deprecation")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    getData(intent);
    self = this;

    // Enter foreground state
    String title = "Service started.";
    String subject = "Service is running.";
    String body = "Monitoring...";
    Notification notification = new Notification(R.drawable.ic_launcher, title,
            System.currentTimeMillis());
    if(notificationSounds)
        notification.defaults |= Notification.DEFAULT_SOUND;
    else
        notification.sound = null;
    Intent notificationIntent = new Intent(this, MainActivity3.class);
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, subject, body, pendIntent);
    startForeground(1500, notification);

    new BatteryLifeTask(appContext).execute();
    return START_NOT_STICKY;
}

这是我的 AsyncTask:

// Looping AsyncTask for continuous mode
private class BatteryLifeTask extends AsyncTask<Void, Void, Void> {

    // Member variables
    Context appContext;
    int batteryPct0;

    public BatteryLifeTask(Context context) {
        super();
        appContext = context;
    }

    protected Void doInBackground(Void... params) {
        System.out.println("Entering doInBackground");
        // Get the initial battery level
        batteryPct0 = getBatteryPercent();
        System.out.println("Initial battery percent: " + batteryPct0);

        // Check time
        Calendar c = Calendar.getInstance();
        Date dateNow = c.getTime();
        // getTime returns ms, need minutes. 60000ms in a minute.
        long currTime = dateNow.getTime() / 60000;

        if(currTime >= timeToUse){
            finished = true;
            stopSelf();
        }

        System.out.println("Leaving doInBackground");
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if(!finished) {
            int waitTime = 60000 * interval; // 1 minute is 60000 miliseconds
            System.out.println("Entering postExecute. waitTime is " + waitTime);
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    if(!finished) { // In case postDelayed is pending, avoids extra notification
                        System.out.println("An interval has passed.");
                        calculateHelper(batteryPct0);
                        new BatteryLifeTask(appContext).execute();
                    }
                }
            };
            Handler h = new Handler();
            h.postDelayed(r, waitTime);
        }
    }
}

这是我创建通知的代码:

// Method for creating a notification
@SuppressWarnings("deprecation")
void notify0(int id, String title, String subject, String body, boolean playSound){
    NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notify = new Notification(android.R.drawable.
    PendingIntent pending = PendingIntent.getActivity(
            getApplicationContext(), 0, new Intent(), 0);
    notify.setLatestEventInfo(getApplicationContext(), subject, body, pending);
    if(playSound)
        notify.defaults |= Notification.DEFAULT_SOUND;
    else
        notify.sound = null;

    // Cancel running notification if exists
    NM.cancel(id);

    // Push notification
    NM.notify(id, notify);
}



谁能帮我?这让我发疯!当插入并连接到 USB 调试时,我的应用程序可以完美运行。但是当拔掉插头时,服务似乎完全停止并且什么都不做。

这是因为您正在 returning START_NOT_STICKY on the Service's onStartCommand()

START_NOT_STICKY if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent).

你应该 return START_STICKY

START_STICKY If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service.

检查此service api changes,尤其是服务生命周期更改部分。

Return START_STICKY 而不是 START_NOT_STICKY 并检查您的设计。在您的情况下,最好使用超时为 5 分钟的 AlarmManager,然后启动 IntentService。