我的Android服务不会继续运行

时间:2015-01-08 15:00:56

标签: java android android-intent android-asynctask android-service

我有一个执行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调试时,我的应用程序完美运行。但是当拔掉插头时,服务似乎完全停止并且什么都不做。

2 个答案:

答案 0 :(得分:2)

这是因为您在服务的START_NOT_STICKY上返回onStartCommand()

  

START_NOT_STICKY 如果有的话   服务的进程在启动时被终止(在返回之后)   onStartCommand(Intent,int,int)),并没有新的开始意图   交付它,然后将服务从启动状态中取出   在将来显式调用之前不要重新创建   Context.startService(意向)。

您应该返回START_STICKY而不是

  

START_STICKY 如果此服务的进程在启动时被终止(从onStartCommand(Intent,int,int)返回后),则   将其保留在启动状态但不保留此意图。   稍后系统将尝试重新创建服务。

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

答案 1 :(得分:0)

返回START_STICKY而不是START_NOT_STICKY并审核您的设计。在你的情况下,最好在5分钟超时时使用AlarmManager,然后启动IntentService。