2016-09-14 72 views
1

我创建一个应用程序与按钮5秒通知我收到通知时,我在应用程序或外部 所以我想获得通知只是当我没有在应用程序 上工作时,当我点击通知进入应用程序并且通知停止时,但当我重新关闭应用程序时,通知每隔5分钟出现一次。如何当我在应用程序中删除我自己的应用程序通知

mainactivity.java

Button button; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
     button = (Button)findViewById(R.id.btn1); 
    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      Calendar calendar =Calendar.getInstance(); 



      Intent intent = new Intent (getApplicationContext(),AlertReceiver.class); 
      PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),100,intent,PendingIntent.FLAG_UPDATE_CURRENT); 

      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); 
      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_FIFTEEN_MINUTES/180,pendingIntent); 


     } 
    }); 

} 

AlertReciver.class

public class AlertReceiver extends BroadcastReceiver { 



@Override 
public void onReceive(Context context, Intent intent) { 
    NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 
    Intent repeating_intent = new Intent(context,Activity12.class); 
    repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

    PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT); 
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setContentIntent(pendingIntent) 
      .setSmallIcon(R.drawable.ic_launcher) 
      .setContentTitle("AAA") 
      .setContentText("BBB") 
      .setAutoCancel(true); 

     notificationManager.notify(100,builder.build()); 

Activity12.class是空的只是TextView的有...!

回答

0

一种可能性是只显示通知,如果应用程序没有运行。因此,您可以为应用程序提供一个静态变量,您可以在构建通知之前检查,在onResume()中设置为true,或者在onPause()中设置为false。

可能有更好的方法来检查应用程序当前是否正在运行,但是我没有在android java中编写一段时间,我现在还没有android studio在这里试用它。