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

Как выполнить метод, нажав на уведомление

У меня есть приложение с двумя кнопками. Одна кнопка, которая "закрывает" приложение и запускает алгоритм. Когда я нажимаю "начинать", он "скрывает" приложение и отображает уведомление в панели уведомлений. Мне нужно иметь возможность выполнять/вызывать метод при нажатии/нажатии на уведомление. На этот вопрос есть несколько ответов, но они невероятно расплывчаты и указывают только на ссылку на документ на BroadcastReceiver.

Если вы собираетесь оставить URL-адрес документа BroadcastReceiver и сказать "прочитайте эту страницу", пожалуйста, не отвечайте на этот вопрос. Если вы собираетесь объяснить, как я могу использовать BroadcastReceiver для выполнения метода (из того же класса, который отобразил уведомление), пожалуйста, покажите мне какой-то код, как это можно сделать.

Мой алгоритм: нажмите кнопку, покажите уведомление, нажмите уведомление, вызовите метод (не отображайте активность). Что это.

Если это невозможно, просто дайте мне знать. Если да, пожалуйста, покажите мне, что вы сделали бы, чтобы это стало возможным. Что-то такое простое не должно было быть упущено разработчиками android sdk.

4b9b3361

Ответ 1

После нескольких итераций проб и ошибок, я наконец нашел довольно простой и чистый способ запуска произвольного метода при нажатии на действие уведомления. В моем решении есть один класс (я буду называть NotificationUtils), который создает уведомление, а также содержит статический внутренний класс IntentService, который будет запускаться при нажатии на действия в уведомлении. Вот мой класс NotificationUtils, за которым следуют необходимые изменения в AndroidManifest.xml:

public class NotificationUtils {
    public static final int NOTIFICATION_ID = 1;

    public static final String ACTION_1 = "action_1";

    public static void displayNotification(Context context) {

        Intent action1Intent = new Intent(context, NotificationActionService.class)
            .setAction(ACTION_1);

        PendingIntent action1PendingIntent = PendingIntent.getService(context, 0,
                action1Intent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_launcher)
                        .setContentTitle("Sample Notification")
                        .setContentText("Notification text goes here")
                        .addAction(new NotificationCompat.Action(R.drawable.ic_launcher,
                                "Action 1", action1PendingIntent));

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
    }

    public static class NotificationActionService extends IntentService {
        public NotificationActionService() {
            super(NotificationActionService.class.getSimpleName());
        }

        @Override
        protected void onHandleIntent(Intent intent) {
            String action = intent.getAction();
            DebugUtils.log("Received notification action: " + action);
            if (ACTION_1.equals(action)) {
                // TODO: handle action 1.
                // If you want to cancel the notification: NotificationManagerCompat.from(this).cancel(NOTIFICATION_ID);
            }
        }
}

Теперь просто выполните свои действия в onHandleIntent и добавьте NotificationActionService в ваш манифест в тегах <application>:

<service android:name=".NotificationUtils$NotificationActionService" />

Резюме:

  • Создайте класс, который будет создавать уведомление.
  • Внутри этого класса добавьте внутренние классы IntentService (убедитесь, что они статичны или вы получите загадочную ошибку!), которые могут запускать любой метод на основе действия, которое было нажато.
  • Объявить класс IntentService в вашем манифесте.

Ответ 2

При уведомлении о щелчке мы не можем получить событие пожара или прослушиватель щелчков. Когда мы добавляем уведомление в панель уведомлений, мы можем установить ожидающее намерение, которое запускает намерение (активность/услуга/трансляция) после щелчка уведомления.

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

// This is what you are going to set a pending intent which will start once
// notification is clicked. Hopes you know how to add notification bar. 
Intent notificationIntent = new Intent(this, dummy_activity.class);
notificationIntent.setAction("android.intent.action.MAIN");
notificationIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                                notificationIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT | 
                                Notification.FLAG_AUTO_CANCEL);

// Now, once this dummy activity starts send a broad cast to your parent activity and finish the pending activity
//(remember you need to register your broadcast action here to receive).
    BroadcastReceiver call_method = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action_name = intent.getAction();
                if (action_name.equals("call_method")) {
                    // call your method here and do what ever you want.
                }
            };
        };
        registerReceiver(call_method, new IntentFilter("call_method"));
    }
}

Ответ 3

protected void displayNotification() {
    Log.i("Start", "notification");

  /* Invoking the default notification service */
    NotificationCompat.Builder  mBuilder =
            new NotificationCompat.Builder(this);
    mBuilder.setAutoCancel(true);

    mBuilder.setContentTitle("New Message");
    mBuilder.setContentText("You've received UnRead message.");
    mBuilder.setTicker("New Message Alert!");
    mBuilder.setSmallIcon(R.drawable.icon2);

  /* Increase notification number every time a new notification arrives */
    mBuilder.setNumber(++numMessages);

  /* Creates an explicit intent for an Activity in your app */

    Intent resultIntent = new Intent(this, FreesmsLog.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(FreesmsLog.class);

  /* Adds the Intent that starts the Activity to the top of the stack */
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  /* notificationID allows you to update the notification later on. */
    mNotificationManager.notify(notificationID, mBuilder.build());

}