Android 当我';我在应用程序上

Android 当我';我在应用程序上,android,notifications,Android,Notifications,我创建了一个应用程序,带有5秒通知按钮。当我在应用程序上或在应用程序外部时,我会收到通知 所以我想在我不使用应用程序的时候收到通知 当我点击通知进入应用程序,通知停止,但当我重新关闭应用程序时,通知每5分钟/秒出现一次 mainactivity.java Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);

我创建了一个应用程序,带有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);


        }
    });

}
AlertReceiver.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是空的,只需文本视图

一种可能性是仅在应用程序未运行时显示通知。因此,您可以为应用程序提供一个静态变量,在生成通知之前进行检查,在onResume()中设置为true,在onPause()中设置为false


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

一种可能是仅在应用程序未运行时才显示通知。因此,您可以为应用程序提供一个静态变量,在生成通知之前进行检查,在onResume()中设置为true,在onPause()中设置为false

可能有更好的方法来检查应用程序是否正在运行,但我已经有一段时间没有用android java编写代码了,而且我现在还没有android studio来尝试