Подтвердить что ты не робот

Как показать значок в строке состояния при запуске приложения, в том числе в фоновом режиме?

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

4b9b3361

Ответ 1

Вы должны иметь возможность сделать это с помощью 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);

Этот код должен быть где-то, где вы уверены, будет запущен, когда ваше приложение запустится. Возможно, в вашем приложении пользовательский Application Object onCreate() метод.

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

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

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

Ответ 2

Для нового 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);

Ответ 3

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

Один из способов достижения цели сохранения значка там, только когда приложение запущено, - инициализировать уведомление в onCreate() и вызвать 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);
    }
}

Ответ 4

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

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);