[英]android notification comes up on start
我正在嘗試創建一個應用程序,在該應用程序中安排一個通知,但是每當我嘗試打開該應用程序時,該通知就會出現.....它會在正確的時間出現,而且在打開應用程序時也會出現。 這是代碼.........
主要活動.java
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Calendar Calendar_Object = Calendar.getInstance();
Calendar_Object.set(Calendar.HOUR_OF_DAY,16);
Calendar_Object.set(Calendar.MINUTE,18);
Calendar_Object.set(Calendar.SECOND,00);
Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,
0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, Calendar_Object.getTimeInMillis(),120000,pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, NotificationService.class);
context.startService(myIntent);
}
}
NotificationService.java
public class NotificationService extends Service {
private NotificationManager mManager;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mManager = (NotificationManager) this.getApplicationContext()
.getSystemService(
this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
@SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.images,
"xys", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
this.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_ONE_SHOT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(),
"xyz", "abcd",
pendingNotificationIntent);
notification.flags|= Notification.FLAG_AUTO_CANCEL;
mManager.notify(0, notification);
stopSelf();
}
警報再次觸發,因為在通知后,您將調用MainActivity,在其中再次設置警報。 嘗試在其他活動中設置鬧鍾。 否則,如果在通知后開始活動,則無法設置警報。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.