Как отобразить значок в строке состояния при запуске приложения, в том числе в фоновом режиме? - PullRequest
26 голосов
/ 20 октября 2010

Я хочу поместить значок в строке состояния, когда мое приложение работает, в том числе, когда оно работает в фоновом режиме. Как я могу это сделать?

Ответы [ 4 ]

19 голосов
/ 20 октября 2010

Вы должны быть в состоянии сделать это с помощью 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 () пользовательского объекта приложения.

Однако после этого все сложно. Убийство приложения может произойти в любое время. Поэтому вы можете попытаться поместить что-то в onTerminate () класса Application, но это не гарантированно будет вызвано.

((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);

будет тем, что нужно для удаления значка.

9 голосов
/ 13 ноября 2015

Для нового 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);
6 голосов
/ 20 октября 2010

Взгляните на руководство разработчика " Создание уведомлений в строке состояния ".

Один из способов достижения цели сохранения значка там только во время работы приложения - инициализация уведомления в onCreate() и вызов cancel(int) в вашем методе onPause(), только если isFinishing() возвращает истину.

Пример:

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);
    }
}
4 голосов
/ 12 апреля 2016

Это действительно работает.Я создал метод из приведенного выше примера:

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 ("Testbar Test", 10);

...