2016-08-10 3 views
0

Я делаю IntentService, который подключается к веб-службе каждые 15 минут и показывает уведомление. Когда приложение открыто, работа по обслуживанию и уведомление было шоу, но когда близко сервисные работы приложения только в Android API < 21.IntentService не работает в Android Lollipop, когда приложение закрывается

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); 
    } 
}); 

ответ

0

В вашем случае лучше использовать уведомления Android, когда ваше приложение закрыто. Таким образом, система уведомляет ваше приложение о том, что доступно что-то новое (вы можете добавить данные в свое уведомление). Это лучше, потому что если кто-то установит ваше приложение и каждые 15 минут подключится к вашему серверу, результатом станет увеличение загруженных данных из вашего приложения и увеличение использования батареи. Прочтите это сообщение для получения дополнительной информации: https://developer.android.com/guide/topics/ui/notifiers/notifications.html

Смежные вопросы