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

Постоянный значок службы в панели уведомлений

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

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

Спасибо.

4b9b3361

Ответ 1

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

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

Ответ 2

Я знаю, что это старый вопрос, но он был первым на странице результатов 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