当app关闭时,IntentService无法在Android Lollipop中运行

时间:2016-08-10 15:39:45

标签: android android-5.0-lollipop intentservice

我制作IntentService,每15分钟连接一次Web服务并显示通知。当应用程序打开时,会显示服务工作和通知,但是当关闭的应用程序服务仅在Android API中工作时< 21。

IntentSerice:

public class NotificationsService extends IntentService {

    private static final String TAG = "NotificationsService";

    public NotificationsService() {
        super(TAG);
    }

@Override
protected void onHandleIntent(Intent intent) {
    ConnectionDetector checkNetwork = new ConnectionDetector(this);
    if (!checkNetwork.isNetworkAvailableAndConnected()) {
        return;
    }

    try {
        // Connect to web service
    } catch (IOException | JSONException e) {
        Log.e(TAG, "Error", e);
    }

    // Show notification
}

public static Intent newIntent(Context context) {
    return new Intent(context, NotificationsService.class);
}

public static void setNotificationServiceAlarm(Context context,
                                               boolean isNotificationEnable) {
    Intent intent = NotificationsService.newIntent(context);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent,
                                                           PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (isNotificationEnable) {

        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                         SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES,
                                         AlarmManager.INTERVAL_FIFTEEN_MINUTES,
                                         pendingIntent);
    } else {
        alarmManager.cancel(pendingIntent);
        pendingIntent.cancel();
    }
}

MainActivity:

Button button = (Button) findViewById(R.id.buttonStartService);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        NotificationsService.setNotificationServiceAlarm(this, true);
    }
});

1 个答案:

答案 0 :(得分:0)

在您的情况下,最好在关闭应用时使用Android通知。通过这种方式,系统会通知您的应用程序有新的可用内容(您可以向通知中添加数据)。这样做更好,因为如果某人安装了您的应用并且每隔15分钟连接到您的服务器,结果就会增加从您的应用下载的数据并增加电池使用量。 阅读这篇文章了解更多信息: https://developer.android.com/guide/topics/ui/notifiers/notifications.html