2016-08-10 5 views
0

15 분마다 웹 서비스에 연결하는 IntentService를 만들고 알림을 표시합니다. 응용 프로그램이 열려있을 때, 서비스 작업 및 알림 표시했지만, 경우에만 안드로이드 API에 가까운 응용 프로그램 서비스 작업 < (21)앱이 닫힐 때 Android Lollipop에서 IntentService가 작동하지 않습니다.

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

관련 문제