Обработка пользовательского нажатия кнопки уведомления в Android

Я работаю над Android приложение, которое в основном музыкальное приложение. Согласно одному из требований, когда песня воспроизводится в музыкальном проигрывателе, уведомление должно также отображаться в notification панель, которая также видна, когда устройство заблокировано. Теперь я создал кастом layout для notification который имеет несколько кнопок для взаимодействия с музыкальным проигрывателем. Я могу видеть уведомление, когда песня играет, но я не могу обработать их щелчки. Я создал BroadcastReceiver тоже. Я искал на SO для этого, погуглил его и применил много решений, данных там, но все же я не в состоянии справиться с этим. Я даже просмотрел это видео, но напрасно до сих пор: Как создать пользовательское уведомление в Android

Я вставляю свой код здесь, пожалуйста, дайте мне знать, где я делаю это неправильно.

NotificationUI как следует: уведомление

Это метод для установки notification,

public void setNotification(String songName,final String image,String songNamear){
    String ns = Context.NOTIFICATION_SERVICE;
    notificationManager = (NotificationManager) getSystemService(ns);

    Thread th=new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(image);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 8;
                image12 = BitmapFactory.decodeStream(input, null, options);
                BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(input, false);
                image12 = decoder.decodeRegion(new Rect(10, 10, 50, 50), null);
            } catch(IOException e) {
                System.out.println(e);
            }
        }
    });
    th.start();
    Notification.Builder mNotifyBuilder = new Notification.Builder(this);
    notification = mNotifyBuilder.setContentTitle(songName)
            .setContentText(songNamear)
            .setSmallIcon(R.drawable.app_icon)
            .setLargeIcon(image12)
            .build();
    mNotifyBuilder.setPriority(Notification.PRIORITY_HIGH);

    notificationView = new RemoteViews(getPackageName(), R.layout.notification_mediacontroller);
    notificationView.setImageViewResource(R.id.btn_play_pause_in_notification,R.drawable.home_stop_icon);
    Log.d("imageuri",""+Uri.parse(image));
    notificationView.setImageViewBitmap(R.id.img_user,image12);
    notificationView.setTextViewText(R.id.txt_songname,songName);
    notificationView.setTextViewText(R.id.txt_songnamear,songNamear);
    SharedPreferences.Editor editor = getSharedPreferences("juke1", MODE_PRIVATE).edit();
    editor.putString("pos",""+intPOs);
    editor.commit();
    Intent notificationIntent = new Intent(this, MusicPlayerActivity.class);
    notificationIntent.putExtra("Position",intPOs);
    notificationIntent.putExtra("page","not");
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.contentView = notificationView;
    notification.contentIntent = pendingNotificationIntent;
    notification.flags |= Notification.FLAG_NO_CLEAR;

    //this is the intent that is supposed to be called when the button is clicked

    Intent switchIntent = new Intent(Constants.NOTIFICATION_CLICK_ACTION);
    switchIntent.setAction(Constants.ACTION_PLAY);
    PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(MusicPlayerActivity.this, 100, switchIntent, 0);

    Intent switchIntent1 = new Intent(Constants.NOTIFICATION_CLICK_ACTION);
    switchIntent1.setAction(Constants.ACTION_NEXT);
    PendingIntent pendingSwitchIntent1 = PendingIntent.getBroadcast(MusicPlayerActivity.this, 101, switchIntent1, 0);

    Intent switchIntent2 = new Intent(Constants.NOTIFICATION_CLICK_ACTION);
    switchIntent2.setAction(Constants.ACTION_PREV);
    PendingIntent pendingSwitchIntent2 = PendingIntent.getBroadcast(MusicPlayerActivity.this, 102, switchIntent2, 0);

    Intent switchIntent3 = new Intent(Constants.NOTIFICATION_CLICK_ACTION);
    switchIntent3.setAction(Constants.ACTION_CLOSE);
    PendingIntent pendingSwitchIntent3 = PendingIntent.getBroadcast(MusicPlayerActivity.this, 103, switchIntent3, 0);

    notificationView.setOnClickPendingIntent(R.id.btn_play_pause_in_notification, pendingSwitchIntent);
    notificationView.setOnClickPendingIntent(R.id.btn_next, pendingSwitchIntent1);
    notificationView.setOnClickPendingIntent(R.id.btn_prev, pendingSwitchIntent2);
    notificationView.setOnClickPendingIntent(R.id.btn_close, pendingSwitchIntent3);
    notificationManager.notify(1, notification);

Ниже приводится BroadcastReceiver, Я попробовал это как отдельный класс, а также внутренний class из MusicPlayerActivity, С внутренней class мне будет легко позвонить functions для следующей песни, предыдущей песни, воспроизведения / паузы и т.д., для которых buttonsclicks предназначены.

public class NotificationListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        MakeToast.show("Clcik");
        String action = intent.getAction();
        if(action.equalsIgnoreCase(Constants.ACTION_NEXT)){
            MakeToast.show("Next");
        }
        if(action.equalsIgnoreCase(Constants.ACTION_PREV)){
            MakeToast.show("Previous");
        }
        if(action.equalsIgnoreCase(Constants.ACTION_CLOSE)){
            MakeToast.show("Close");
        }
        if(action.equalsIgnoreCase(Constants.ACTION_PLAY)){
            MakeToast.show("Play");
        }

    }
}

В Android ManifestПолучатель объявляется следующим образом. На данный момент он находится в отдельном class,

<receiver android:name=".listeners.NotificationListener">
        <intent-filter>
            <action android:name="notification_button_clicked" />
        </intent-filter>
    </receiver>

Буду признателен за любую помощь, так как я очень опаздываю с расписанием.

Спасибо

1 ответ

Вы можете использовать класс обслуживания для обработки нажатий кнопок с помощью удаленного просмотра уведомлений.

public class MusicPlayerService extends Service {
public static final String ACTION_PAUSE_PLAY = PACKAGE_NAME + ".playpause";
public static final String ACTION_NEXT = PACKAGE_NAME + ".next";
public static final String ACTION_PREVIOUS = PACKAGE_NAME + ".prev";


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction() != null) {

        switch (intent.getAction()) {
            case ACTION_PREVIOUS:
                // go to previous song
                break;
            case ACTION_NEXT:
                // go to next song
                break;
            case ACTION_PAUSE_PLAY:
                // pause or play song
                break;
        }
    }
    return START_NOT_STICKY;
}

Также вы должны связать кнопки уведомлений с намерением ожидания

 PendingIntent pendingIntent;

    final ComponentName serviceName = new ComponentName(service, MusicPlayerService.class);

    // Previous track
    pendingIntent = buildPendingIntent(service, ACTION_PREVIOUS, serviceName);
    notificationLayout.setOnClickPendingIntent(R.id.prev, pendingIntent);

    // Play and pause
    pendingIntent = buildPendingIntent(service, ACTION_PAUSE_PLAY, serviceName);
    notificationLayout.setOnClickPendingIntent(R.id.playpause, pendingIntent);

    // Next track
    pendingIntent = buildPendingIntent(service, ACTION_NEXT, serviceName);
    notificationLayout.setOnClickPendingIntent(R.id.next, pendingIntent);
Другие вопросы по тегам