Постоянный значок службы в панели уведомлений - PullRequest
24 голосов
/ 31 марта 2012

Я пытаюсь выяснить, как показать, что моя служба работает со значком постоянного уведомления.Многие примеры, которые я нашел, только отправляют отклоняемое сообщение в панель уведомлений.Мне нужен постоянный значок, который, когда вы опускаете панель уведомлений, показывает, что служба запущена, и вы можете щелкнуть по ней, чтобы открыть приложение, чтобы отключить службу.как это сделать, любой APK это нормально, но хотелось бы работать с 4.0 и выше.

Спасибо.

Ответы [ 2 ]

36 голосов
/ 31 марта 2012

это должно быть то же самое, что и отклоняемое сообщение, за исключением того, что вы изменили флаг.

Notification.FLAG_ONGOING_EVENT

вместо

Notification.FLAG_AUTO_CANCEL

При нажатии на уведомление запускается отправляемое вами намерение, поэтому вы должны убедиться, что Activity выполняет то, что вам нужно.

private void showRecordingNotification(){
    Notification not = new Notification(R.drawable.icon, "Application started", System.currentTimeMillis());
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, main.class), Notification.FLAG_ONGOING_EVENT);        
    not.flags = Notification.FLAG_ONGOING_EVENT;
    not.setLatestEventInfo(this, "Application Name", "Application Description", contentIntent);
    mNotificationManager.notify(1, not);
}
20 голосов
/ 10 апреля 2015

Я знаю, что это старый вопрос, но он был первым на странице результатов Google, поэтому я добавлю информацию, чтобы помочь другим.

Постоянные уведомления

Хитрость в том, чтобы добавить .setOngoing к вашему NotificationCompat.Builder

Кнопка закрытия

Кнопка, которая открывает приложение и закрывает сервис, требует PendingIntent

Пример

В этом примере показано постоянное уведомление с кнопкой закрытия, которая выходит из приложения.

MyService:

private static final int NOTIFICATION = 1;
public static final String CLOSE_ACTION = "close";
@Nullable
private NotificationManager mNotificationManager = null;
private final NotificationCompat.Builder mNotificationBuilder = new NotificationCompat.Builder(this);

private void setupNotifications() { //called in onCreate()
    if (mNotificationManager == null) {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP),
            0);
    PendingIntent pendingCloseIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)
                    .setAction(CLOSE_ACTION),
            0);
    mNotificationBuilder
            .setSmallIcon(R.drawable.ic_notification)
            .setCategory(NotificationCompat.CATEGORY_SERVICE)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setContentTitle(getText(R.string.app_name))
            .setWhen(System.currentTimeMillis())
            .setContentIntent(pendingIntent)
            .addAction(android.R.drawable.ic_menu_close_clear_cancel,
                    getString(R.string.action_exit), pendingCloseIntent)
            .setOngoing(true);
}

private void showNotification() {
    mNotificationBuilder
            .setTicker(getText(R.string.service_connected))
            .setContentText(getText(R.string.service_connected));
    if (mNotificationManager != null) {
        mNotificationManager.notify(NOTIFICATION, mNotificationBuilder.build());
    }
}

MainActivity должен обрабатывать близкие намерения.

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String action = intent.getAction();
    if (action == null) {
        return;
    }
    switch (action) {
        case MyService.CLOSE_ACTION:
            exit();
            break;
    }
}    

private void exit() {
    stopService(new Intent(this, MyService.class));
    finish();
}

AnotherActivity должно быть закончено и отправить намерение на выход MainActivity

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    String action = intent.getAction();
    if (action == null) {
        return;
    }
    switch (action) {
        case MyService.CLOSE_ACTION:
            exit();
            break;
    }
}

/**
 * Stops started services and exits the application.
 */
private void exit() {
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setAction(Stn1110Service.CLOSE_ACTION);
    startActivity(intent);
}

Может кто-нибудь указать мне ресурсы или учебник

http://developer.android.com/training/notify-user/build-notification.html

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...