2016-11-12 3 views
0

지속적인 알림을받을 수 있도록 서비스를 만들었습니다. 이 알림에 다른 활동에 의도를 보낼 수있는 옵션이 필요합니다.서비스를 사용하여 작업을 수행 할 수있는 지속적인 알림을 시작하십시오.

옵션은 본질적으로 앱이 스폰 된 모든 프로세스를 중지합니다. 따라서 작업이 눌러지면 알림을 닫아야합니다.

보류중인 브로드 캐스트 인 텐트를 사용하여이 작업을 수행하려고하지만 어떤 이유로 브로드 캐스트 수신기가 의도를 포착하지 못합니다. 서비스의 onCreate() 메소드에서 수신기를 동적으로 등록하고 서비스의 onDestroy() 메소드에서 수신기의 등록을 취소합니다. onHandleIntent() 방법이 끝난 후

public class myService extends IntentService { 
    private boolean shown = false; 
    private ButtonReceiver buttonReceiver; 

    //Side note: this is legacy code. Necessary? 
    public myService() { 
     super("myService"); 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

     IntentFilter filter = new IntentFilter("com.myapp.KILL_NOTIFICATION"); 
     this.buttonReceiver = new ButtonReceiver(); 
     this.registerReceiver(this.buttonReceiver, filter); 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     unregisterReceiver(this.buttonReceiver); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 

     if(intent.getAction() == "com.myapp.START_SERVICE") { 
      //generate a unique id for the notification 
      int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.US).format(new Date())); 

      //create a pending intent to send off when the kill action is pressed 
      Intent buttonIntent = new Intent("com.myapp.KILL_NOTIFICATION"); 
      buttonIntent.putExtra("notificationId", id); 
      PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent, 0); 

      Notification.Builder builder = new Notification.Builder(getApplicationContext()); 
      builder.setAutoCancel(false); 
      builder.setContentTitle("my app"); 
      //builder.setContentText("Press this notification to kill."); 
      builder.setOngoing(true); 
      builder.setSmallIcon(R.drawable.ic_launcher); 
      //builder.setContentIntent(pendingIntent); 
      builder.addAction(R.drawable.ic_clear_black_24dp, "Kill my app", btPendingIntent); 
      builder.setWhen(0); 
      builder.setPriority(Notification.PRIORITY_MAX); 

      Notification notification = builder.build(); 
      NotificationManager notificationManager = 
        (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
      //TODO need to find first unused notif id 
      notificationManager.notify(id, notification); 
     } 
    } 

    public class ButtonReceiver extends BroadcastReceiver { 

     @Override 
     public void onReceive(Context context, Intent intent) { 

      int notificationId = intent.getIntExtra("notificationId", 0); 

      Intent killIntent = new Intent("com.myapp.KILL_EVERYTHING"); 
      killIntent.addCategory(Intent.CATEGORY_DEFAULT); 
      startActivity(killIntent); 

      //cancel notification 
      NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); 
      notificationManager.cancel(notificationId); 
     } 
    } 
} 

답변

1

IntentService 그래서 당신의 동적 등록 된 수신기가 발생했을 때 방송을 얻기 위해 주변에 더 이상 없다, 그 자체를 중지합니다.

진행중인 Notification을 유지하기 위해 Service이 필요하지 않습니다. 귀하의 경우에는 Service을 시작하는 대신 Notification을 직접 발행하면됩니다. 그런 다음 수신자 클래스를 매니페스트에 정적으로 등록하고 명시적인 Intent을 사용하여 Notification에서 브로드 캐스트합니다.

그것의 자신의 클래스 파일로 이동 ButtonReceiver, 그래서 같은 매니페스트에 등록이 :

<receiver android:name=".ButtonReceiver" /> 

당신은 당신이 getSystemService()을처럼, onReceive()에 전달 된 context 매개 변수에 startActivity()를 호출해야합니다. 다음 플래그를 Intent에 추가해야합니다. 대한

killIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

그럼 그냥 변경 buttonIntent

NotificationPendingIntent에 :

Intent buttonIntent = new Intent(this, ButtonReceiver.class); 

ButtonReceiver가 처리 할 수있는 유일한 방송이 있다면, 당신은 정말 더 이상 KILL_NOTIFICATION 조치를 필요가 없습니다.

+0

서비스를 사용하려는 이유는 "기본"활동이 지속되지 않기 때문입니다. 인 텐트를 사용하여 의사 결정을 내리는 다른 여러 모듈과 앱의 제어 흐름으로 존재합니다. 제어 흐름이 완료되면 (1 초 미만) 앱이 종료되어 배경에 남아 있지 않게됩니다. 진행중인 알림은 모든 것을 종료 할 수 있도록이 주 활동에 의도를 보내야합니다. 주 활동에 의해 시작된 경우 알림은 계속 유지됩니까? – FutureShocked

+1

예. 'onHandleIntent()'가 끝난 직후'IntentService'가 끝나기 때문에 현재는'Notification'을 지속하지 않는 컴포넌트로부터'Notification'을 발행하고 있습니다 -'Notification'이 여전히 주위에 붙어 있습니까? 나 자신도 부팅 수신기에서 진행중인'알림 '을 발행하는 개인용 앱을 사용한다. 이제까지'활동 '이나'서비스 '를 시작한 적이 없다. 진행중인'알림 '은 앱이 프로그래밍 방식으로 제거하거나 앱이 어떻게 든 강제 중지 될 때까지 실제로 아무데도 진행되지 않습니다. –

+1

굉장합니다. 그게 다 맞아. 나는 그것을 구현하고 시험 할 기회를 얻 자마자 당신의 대답을 받아 들일 것입니다. 당신의 도움을 주셔서 감사합니다! – FutureShocked

관련 문제