2017-04-24 56 views
1

我有一個Android應用程序,它將播放在線廣播,甚至用戶最小化應用程序。我想要做的是,當用戶按下通知時,它應該停止或銷燬我的主要活動,我有通過通知打開主要活動的代碼,並且它工作正常,我想按每畝更改代碼關心,我需要的是一些幫助...我想通過通知停止主要活動

NotificationCompat.Builder builder=new NotificationCompat.Builder(this); 
    builder.setSmallIcon(R.drawable.ic); 
    builder.setContentTitle("RadioPlanet"); 
    builder.setContentText("Touch here to Open");int mll=001; 
    PendingIntent contentIntent = 
      PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); 

    builder.setContentIntent(contentIntent); 
    NotificationManager mNotification=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); 
    mNotification.notify(mll,builder.build()); 

添加答案的OnCreate

BroadcastReceiver mReceiver = new BroadcastReceiver() { 

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

    }; 


    IntentFilter filter = new IntentFilter("android.intent.CLOSE_ACTIVITY"); 
    registerReceiver(mReceiver, filter); 






    NotificationCompat.Builder builder=new NotificationCompat.Builder(this); 
    builder.setSmallIcon(R.drawable.ic); 
    builder.setContentTitle("RadioPlanet"); 
    builder.setContentText("Touch here to Open");int mll=001; 
    Intent intent = new Intent("android.intent.CLOSE_ACTIVITY"); 


    Context context=getApplicationContext(); 

    PendingIntent pIntent = PendingIntent.getBroadcast(context, 0 , intent, 0); 


    builder.setContentIntent(pIntent); 


    NotificationManager mNotification=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); 
    mNotification.notify(mll,builder.build()); 

回答

1

嘗試使用廣播接收器用於這一目的後。

BroadcastReceiver mReceiver = new BroadcastReceiver() { 

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

}; 
在活動的onCreate()

然後

IntentFilter filter = new IntentFilter("android.intent.CLOSE_ACTIVITY"); 
registerReceiver(mReceiver, filter); 

然後您在您的通知的PendingIntent應該有一個包的活動的包

的「android.intent.CLOSE_ACTIVITY」和安全行動

由於

Intent intent = new Intent("android.intent.CLOSE_ACTIVITY"); 
PendingIntent pIntent = PendingIntent.getBroadcast(context, 0 , intent, 0); 

然後用它添加到您的通知使用Notification.Builder構建通知時的setContentIntent(pIntent)。

+0

如何通過通知調用接收器 –

+0

我在編輯我的回答 –

+0

它的工作原理?不要忘記接受答案,如果它的工作 –