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

Событие OnClick для кнопки в пользовательском уведомлении

У меня есть пользовательское уведомление с помощью кнопки. Чтобы установить уведомление и использовать событие OnClick на моей кнопке, я использовал этот код:

//Notification and intent of the notification 
Notification notification = new Notification(R.drawable.stat_notify_missed_call,
            "Custom Notification", System.currentTimeMillis());

Intent mainIntent = new Intent(getBaseContext(), NotificationActivity.class);
PendingIntent pendingMainIntent = PendingIntent.getActivity(getBaseContext(),
    0, mainIntent , 0);
notification.contentIntent = pendingMainIntent;

//Remoteview and intent for my button
RemoteViews notificationView = new RemoteViews(getBaseContext().getPackageName(),
    R.layout.remote_view_layout);

Intent activityIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:190"));
PendingIntent pendingLaunchIntent = PendingIntent.getActivity(getBaseContext(), 0,
            activityIntent, PendingIntent.FLAG_UPDATE_CURRENT);

notificationView.setOnClickPendingIntent(R.id.button1,
    pendingLaunchIntent);

notification.contentView = notificationView;

notificationManager.notify(CUSTOM_NOTIFICATION_ID, notification);

С помощью этого кода у меня есть пользовательское уведомление с моим пользовательским макетом... но я не могу нажать кнопку! каждый раз, когда я пытаюсь щелкнуть кнопку, я нажимаю на все уведомление, и поэтому script запускает "mainIntent" вместо "activityIntent".

Я прочитал в Интернете, что этот код не работает на всех терминалах. Я пробовал это на эмуляторе и на HTC Magic, но у меня всегда такая же проблема: я не могу нажать кнопку!

Мой код прав? кто-то может мне помочь?

Спасибо,

Симона

4b9b3361

Ответ 1

Я пишу код в классе MyActivity.java, который расширяет android.app.Activity

Он создает настраиваемое уведомление, когда пользователь нажимает кнопку, на которую он отправляет broadcast. Существует широковещательный приемник, который принимает broadcast.

private void createDownloadNotification() {
        Intent closeButton = new Intent("Download_Cancelled");
        closeButton.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, closeButton, 0);

        RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.widget_update_notification);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_launcher).setTicker("Ticker Text").setContent(notificationView);
        notificationView.setProgressBar(R.id.pb_progress, 100, 12, false);
        notificationView.setOnClickPendingIntent(R.id.btn_close, pendingSwitchIntent);

        notificationManager.notify(1, builder.build());

    }


public static class DownloadCancelReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            System.out.println("Received Cancelled Event");
        }
    }

Зарегистрировать приемник в AndroidManifest.xml

<receiver android:name=".MainActivity$DownloadCancelReceiver" android:exported="false">
            <intent-filter>
                <action android:name="Download_Cancelled" />
            </intent-filter>
        </receiver>

Так как это внутренний класс, поэтому нужно использовать знак $

Виджет xml находится здесь

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/btn_close"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Close Me" />

    <ProgressBar
        android:id="@+id/pb_progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Ответ 2

проверьте это

  • Создайте файл макета xml для вашего уведомления.

  • Создайте уведомление с помощью Notification.Builder. После добавления всего, что вы хотите (значки, звуки и т.д.), Выполните следующее:

    //R.layout.notification_layout is from step 1
    
    RemoteViews contentView=new RemoteViews(ctx.getPackageName(), R.layout.notification_layout);
    
    setListeners(contentView);//look at step 3
    
    notification.contentView = contentView;
    
  • Создайте метод setListeners. Внутри этого метода вы должны написать это:

    //HelperActivity will be shown at step 4
    
    Intent radio=new Intent(ctx, packagename.youractivity.class);  
    radio.putExtra("AN_ACTION", "do");//if necessary
    
    PendingIntent pRadio = PendingIntent.getActivity(ctx, 0, radio, 0);
    //R.id.radio is a button from the layout which is created at step 2                  view.setOnClickPendingIntent(R.id.radio, pRadio); 
    
    //Follows exactly my code!
    Intent volume=new Intent(ctx, tsapalos11598712.bill3050.shortcuts.helper.HelperActivity.class);
    volume.putExtra("DO", "volume");
    
    //HERE is the whole trick. Look at pVolume. I used 1 instead of 0.
    PendingIntent pVolume = PendingIntent.getActivity(ctx, 1, volume, 0);
    view.setOnClickPendingIntent(R.id.volume, pVolume);
    
  • Для моих требований я использовал HelperActivity, который отвечает на намерения. Но для вас я не думаю, что это необходимо.

Если вам нужен полный исходный код, вы можете просмотреть его или загрузить с моего репозитория git. Код предназначен для личного использования, поэтому не ожидайте, что прочитайте великолепный код с большим количеством комментариев. https://github.com/BILLyTheLiTTle/AndroidProject_Shortcuts

ВСЕ ВЫШЕ, ОТВЕТИТ ВОПРОС ОБ УБЫТКЕ СОБЫТИЙ ОТ РАЗНЫХ КНОПКОВ.

Об отмене уведомления я перенаправляю вас сюда (Как очистить уведомление в Android). Просто не забудьте использовать идентификатор, который вы проанализировали при методе уведомления, когда вы вызывали уведомление в первый раз

Ответ 3

кажется, что setOnClickPendingIntent не работает при использовании внутри коллекций.

Итак, попробуйте setPendingIntentTemplate вместо setOnClickPendingIntent. для получения дополнительной информации ниже ссылки разработчика Android...

Нажмите здесь для получения дополнительной информации - посетите сайт разработчика Android.