Как показать значок в строке состояния при запуске приложения, в том числе в фоновом режиме?
Я хочу поместить значок в строку состояния, когда когда-либо запускается мое приложение, в том числе, когда оно работает в фоновом режиме. Как я могу это сделать?
Вы должны быть в состоянии сделать это с помощью Notification и NotificationManager. Однако получение гарантированного способа узнать, когда ваше приложение не работает, – трудная часть.
Вы можете получить базовую функциональность того, что вы хотите, делая что-то вроде:
Notification notification = new Notification(R.drawable.your_app_icon, R.string.name_of_your_app, System.currentTimeMillis()); notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; NotificationManager notifier = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notifier.notify(1, notification);
Этот код должен быть где-то, где вы уверены, будет запущен, когда ваше приложение запустится. Возможно, в методе onCreate () пользовательского Application Application объекта.
Однако после этого все сложно. Убийство приложения может произойти в любое время. Таким образом, вы можете попытаться поместить что-то в class onTerminate () classа Application, но это не гарантируется.
((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
будет тем, что необходимо для удаления значка.
Для нового API вы можете использовать NotificationCompat.Builder
–
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("Title"); Intent resultIntent = new Intent(this, MyActivity.class); PendingIntent resultPendingIntent = PendingIntent.getActivity( this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); Notification notification = mBuilder.build(); notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNotifyMgr.notify(NOTIFICATION_ID, notification);
Он покажет, пока приложение будет запущено, а кто-то вручную закроет ваше приложение. Вы всегда можете отменить свое уведомление, позвонив –
mNotifyMgr.cancel(NOTIFICATION_ID);
Взгляните на Руководство разработчика « Создание уведомлений о строках состояния ».
Одним из способов достижения цели сохранения значка там, только когда приложение работает, является инициализация уведомления в onCreate()
и cancel(int)
вызова cancel(int)
в вашем onPause()
только если isFinishing()
возвращает true.
Пример:
private static final int NOTIFICATION_EX = 1; private NotificationManager notificationManager; @Override public void onCreate() { super.onCreate(); notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); int icon = R.drawable.notification_icon; CharSequence tickerText = "Hello"; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); Context context = getApplicationContext(); CharSequence contentTitle = "My notification"; CharSequence contentText = "Hello World!"; Intent notificationIntent = new Intent(this, MyClass.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); notificationManager.notify(NOTIFICATION_EX, notification); } @Override protected void onPause() { super.onPause(); if (isFinishing()) { notificationManager.cancel(NOTIFICATION_EX); } }
Это действительно работает. Я создал метод из приведенного выше примера:
private void applyStatusBar(String iconTitle, int notificationId) { NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle(iconTitle); Intent resultIntent = new Intent(this, ActMain.class); PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); Notification notification = mBuilder.build(); notification.flags |= Notification.FLAG_NO_CLEAR|Notification.FLAG_ONGOING_EVENT; NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); mNotifyMgr.notify(notificationId, notification);}
Его следует называть как: applyStatusBar («Тест панели состояния», 10);