2017-01-25 2 views
0

меня уведомление с 2 действиями,близко уведомление с установленным близким расстоянием действия в Android

enter image description here

Закрыть кнопку должно закрыть уведомление и его обслуживание.

 public class TimerService extends Service { 
     ...   

    private void setupNotification(String s) { 
      Intent notificationIntent_Restore = new Intent(this,Adult1Activity.class); 
      notificationIntent_Restore.putExtra(EXTRA_NOTE,NOTE_RESTORE); 
      PendingIntent restoreIntent = PendingIntent.getActivity(this, 
        0, notificationIntent_Restore, PendingIntent.FLAG_UPDATE_CURRENT); 

      final Intent notificationIntent_Close = new Intent(this, Adult1Activity.class); 
      notificationIntent_Close.putExtra(EXTRA_NOTE, NOTE_CLOSE); 
      PendingIntent closeIntent = PendingIntent.getActivity(this, 
        1, notificationIntent_Close, PendingIntent.FLAG_CANCEL_CURRENT); 




      notification = new NotificationCompat.Builder(this) 
        .setSmallIcon(R.mipmap.ic_launcher) 
        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) 
        .setContentTitle("Stand Up!") 
        .setContentText(s) 
        .setAutoCancel(true) 
        .addAction(new NotificationCompat.Action(R.drawable.ic_note_close, "Close", closeIntent)) 
        .addAction(new NotificationCompat.Action(R.drawable.ic_note_restore, "Restore", restoreIntent)) 
        .setContentIntent(restoreIntent); 

      notificationManager.notify(0, notification.build()); 
     } 

Я хочу закрыть его с помощью ЗАКРЫТОГО действия. Я использую этот код в классе AdultActivity:

@Override 
protected void onNewIntent(Intent intent) { 
    super.onNewIntent(intent); // Make sure to call super 
    handleIntent(intent); 
} 

private void handleIntent(Intent intent) { 
    final String a = intent.getStringExtra(EXTRA_NOTE); 
    if (a != null) { 
     switch (a) { 
      case NOTE_RESTORE: 
       //stopBTN.setVisibility(View.VISIBLE); 
       break; 

      case NOTE_CLOSE: 
       stopService(serviceIntent); 
       CloseApp(); 
       break; 
     } 
    } 
} 

, наконец мое приложение купирован и

01/25 11:45:05: Launching app 
Cold swapped changes. 
$ adb shell am start -n "standup.maxsoft.com.standup/standup.maxsoft.com.standup.help.HelpActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER 
Client not ready yet..Waiting for process to come online 
Connected to process 2777 on device emulator-5554 
W/art: Suspending all threads took: 7.291ms 
I/art: Background sticky concurrent mark sweep GC freed 11717(1506KB) AllocSpace objects, 45(768KB) LOS objects, 71% free, 1054KB/3MB, paused 8.582ms total 74.057ms 
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true 

        [ 01-25 11:44:44.661 2777: 2777 D/   ] 
        HostConnection::get() New Host Connection established 0xa32f3910, tid 2777 


        [ 01-25 11:44:44.715 2777: 2798 D/   ] 
        HostConnection::get() New Host Connection established 0xa32f3ec0, tid 2798 
I/OpenGLRenderer: Initialized EGL, version 1.4 
W/EGL_emulation: eglSurfaceAttrib not implemented 
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa32fec80, error=EGL_SUCCESS 
W/EGL_emulation: eglSurfaceAttrib not implemented 
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa32e2500, error=EGL_SUCCESS 
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7d7d30 
W/EGL_emulation: eglSurfaceAttrib not implemented 
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa32e2aa0, error=EGL_SUCCESS 
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7d8cf0 
W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed. 
W/EGL_emulation: eglSurfaceAttrib not implemented 
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xa32e2aa0, error=EGL_SUCCESS 
I/art: Background partial concurrent mark sweep GC freed 4628(216KB) AllocSpace objects, 5(200KB) LOS objects, 40% free, 3MB/5MB, paused 12.525ms total 31.801ms 
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4013960 
E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab7d8dd0 
Application terminated. 

что я могу сделать?

EDIT:

public class TimerService extends Service { 
    public CountingDownTimer countingDownTimer; 
    public static int totalSeconds; 
    public static String timeString=null; 
    public static long seconds_for_compare; 


    public SharedPreferences sharedPreferences; 

    public static NotificationCompat.Builder notification; 
    public static NotificationManager notificationManager; 
    private static final String EXTRA_NOTE = "NOTE"; 
    private static final String NOTE_RESTORE = "restore"; 
    private static final String NOTE_CLOSE = "close"; 



    private static final String ACTION_CLOSE = "ACTION_CLOSE"; 


    @Override 
    public void onCreate() { 

    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     countingDownTimer = new CountingDownTimer(totalSeconds,500); //milliseconds , (500 means) onTick function will be called at every 500 
     countingDownTimer.start(); 

     notificationManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     setupNotification(TimerService.timeString); 

     sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); 

     if (intent != null) { 
      final String action = intent.getAction(); 
      switch (action) { 
       case ACTION_CLOSE: 
        stopSelf(); 
        break; 
      } 
     } 
     // return START_NOT_STICKY; 
     return super.onStartCommand(intent, flags, startId); 
    } 

    @Nullable 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     countingDownTimer.cancel(); 
     notificationManager.cancelAll(); 
     Adult1Activity.onFinish(); 
    } 


    //****************Notification ******************** 
    private void setupNotification(String s) { 

     Intent notificationIntent_Restore = new Intent(this,Adult1Activity.class); 
     notificationIntent_Restore.putExtra(EXTRA_NOTE,NOTE_RESTORE); 
     PendingIntent restoreIntent = PendingIntent.getActivity(this, 
       0, notificationIntent_Restore, PendingIntent.FLAG_UPDATE_CURRENT); 

     final Intent notificationIntent_Close = new Intent(this, TimerService.class); 
     notificationIntent_Close.setAction(ACTION_CLOSE); // use Action 
     PendingIntent closeIntent = PendingIntent.getService(this, 
       1, notificationIntent_Close, PendingIntent.FLAG_UPDATE_CURRENT); 


     notification = new NotificationCompat.Builder(this) 
       .setSmallIcon(R.mipmap.ic_launcher) 
       .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) 
       .setContentTitle("Stand Up!") 
       .setContentText(s) 
       .setAutoCancel(false) 
       .addAction(new NotificationCompat.Action(R.drawable.ic_note_close, "Close", closeIntent)) 
       .addAction(new NotificationCompat.Action(R.drawable.ic_note_restore, "Restore", restoreIntent)) 
       .setContentIntent(restoreIntent); 

     notificationManager.notify(0, notification.build()); 
    } 
+0

что вопрос здесь? –

+0

с нажатием кнопки Закрыть, ничего не происходит. –

+0

Я думаю, что проблема в Adult1Activity/onNewIntent + handleIntent, потому что я chekc это с добавлением тоста. –

ответ

1

Если вы просто хотите, чтобы остановить службу из уведомления, вам не нужно беспокоиться активность.

в службе, определяют действия для закрытия:

private static final String ACTION_CLOSE = "ACTION_CLOSE"; 

// in setupNotification(): 

final Intent notificationIntent_Close = new Intent(this, TimerService.class); 
notificationIntent_Close.setAction(ACTION_CLOSE); // use Action 
PendingIntent closeIntent = PendingIntent.getService(this, 
     1, notificationIntent_Close, PendingIntent.FLAG_UPDATE_CURRENT); 

В службе, ручка действие

@Override 
public int onStartCommand(final Intent intent, final int flags, 
      final int startId) { 
    if (intent != null) { 
     final String action = intent.getAction(); 
     if (action != null) { 
      switch (action) { 
       case ACTION_CLOSE: 
        stopSelf(); 
        break; 
      } 
     } 
    } 
    return START_NOT_STICKY; 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    notificationManager.cancel(0); 
} 
+0

спасибо! но есть проблема. эта служба начинается с нажатия на StartBTN, и когда я нажимаю на новый код редактирования, приложение останавливается и показывает - 'java.lang.RuntimeException: не удается запустить [email protected] с Intent { cmp = standup.maxsoft.com.standup/.home.TimerService}: java.lang.NullPointerException: попытка вызвать виртуальный метод «int java.lang.String.hashCode()» в ссылке на нулевой объект ». что мне делать? –

+0

@MinaDahesh, извините, я забыл добавить проверку, если действие не является нулевым в 'onStartCommand()'. См. Мой отредактированный ответ. –

+0

Я делаю это: вместо использования switch я использую 'if (action! = Null && action == ACTION_CLOSE) {...}'. и его работы! Большое спасибо! –