简体   繁体   English

如何在android中构建通知并实现点击监听器?

[英]How to build a notification in android and implement click listener?

Hello friends i am creating mp3 player application my application is successfully build i want implement click event notification when user goes on background they control media from notification panel my notification also build successfully but problem is that how control music and change image on notification .addaction() when user click on pause the image change to play and when song is play image back change to pause and media player is also and i am also want get songs title, and artist here my code you can easily understand!你好朋友我正在创建 mp3 播放器应用程序我的应用程序已成功构建我想在用户进入后台时实现单击事件通知他们从通知面板控制媒体我的通知也成功构建但问题是如何控制音乐和更改通知中的图像 .addaction( ) 当用户单击暂停图像更改播放和歌曲播放时图像更改更改为暂停和媒体播放器也是,我也想获得歌曲标题,艺术家在这里我的代码你很容易理解!

public void play(int songindex) {
song = songList.get(songindex);

try {

    if (mediaPlayer != null) {
        mediaPlayer.release();
        mediaPlayer = null;
    }
    Uri uri = Uri.parse("file:///" + song.getGetpath());
    mediaPlayer = MediaPlayer.create(mContext, uri);
     title.setText(song.getTitle());
    artist.setText(song.getArtist());

     notificationTitleText=title.getText();
    notificationDescText=artist.getText();
    handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getApplicationContext(), mediaPlayer);
    audioVisualization.linkTo(handler);
    mediaPlayer.start();
    seekBar.setProgress(0);
    seekBar.setMax(100);
    updateProgressBar();

    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
        play.setVisibility(View.GONE);
        pause.setVisibility(View.VISIBLE);
        play_main.setVisibility(View.GONE);
        pause_main.setVisibility(View.VISIBLE);
        Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
        rotate.startAnimation(aniRotate);

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {


                if (checked) {
                    mediaPlayer.setLooping(true);
                    mediaPlayer.start();
                } else if (isShuffle) {
                    // shuffle is on - play a random song
                    Random rand = new Random();
                    currentSongIndex = rand.nextInt((songList.size() - 1) - 0 + 1) + 0;
                    play(currentSongIndex);
                } else {
                    // no repeat or shuffle ON - play next song
                    if (currentSongIndex < (songList.size() - 1)) {
                        play(currentSongIndex + 1);
                        currentSongIndex = currentSongIndex + 1;
                    } else {
                        // play first song
                        play(0);
                        currentSongIndex = 0;
                    }
                }
            }
        });
    }


} catch (Exception e) {

    Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_SHORT).show();


}

} }

public  void  shownotification(){
    Bitmap largeImage = BitmapFactory.decodeResource(getResources(),R.drawable.dog);




    Notification channel = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID_1)
            .setSmallIcon(R.drawable.ic_music)
            .setContentTitle(notificationTitleText
            )
            .setContentText(notificationDescText)
            .setLargeIcon(largeImage)
            .addAction(R.drawable.ic_like,"like",null)
            .addAction(R.drawable.ic_prev,"prev",null)
            .addAction(R.drawable.ic_pause,"pause",null)
            .addAction(R.drawable.ic_next,"next",null)
            .addAction(R.drawable.ic_dislike,"dislike",null)
            .setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle().
                    setShowActionsInCompactView(1,2,3))
            .build();



    mNotificationManagerCompat.notify(1,channel);

}

gettext()method is working fine but it work on first when any clicked event is happen if song play oncomplete and next song is not get text value gettext() 方法工作正常,但如果歌曲播放完成且下一首歌曲未获得文本值,则在发生任何点击事件时它首先工作

I am assuming that you are playing songs from an Activity but this will also work for a service.我假设您正在播放 Activity 中的歌曲,但这也适用于服务。

Put this in your activity or service把它放在你的活动或服务中

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals("com.mypackage.ACTION_PAUSE_MUSIC")){
            //Do whatever you want. Ex. Pause
        }
        //Similarly this can be done for all actions
    }};

Make your show notification method like this让你的节目通知方法像这​​样

public  void  shownotification(){
Bitmap largeImage = BitmapFactory.decodeResource(getResources(),R.drawable.dog);

Intent pauseIntent = new Intent("com.mypackage.ACTION_PAUSE_MUSIC");
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 1, pauseIntent, 0);
// Similarly you can create an intent and pending intent pair for each action you want just change the string in intent constructor

Notification channel = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID_1)
        .setSmallIcon(R.drawable.ic_music)
        .setContentTitle(notificationTitleText
        )
        .setContentText(notificationDescText)
        .setLargeIcon(largeImage)
        .addAction(R.drawable.ic_like,"like",null)
        .addAction(R.drawable.ic_prev,"prev",null)
        .addAction(R.drawable.ic_pause,"pause",pausePendingIntent)  //like this attach every action with respective pending intent
        .addAction(R.drawable.ic_next,"next",null)
        .addAction(R.drawable.ic_dislike,"dislike",null)
        .setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
        .setShowActionsInCompactView(1,2,3))
        .build();

mNotificationManagerCompat.notify(1,channel);}

I want to add one more thing to @Kumar Manas answer我想在@Kumar Manas 的回答中再添加一件事

ie We need to register reciever that is being created in activity.即我们需要注册在活动中创建的接收器。

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals("com.mypackage.ACTION_PAUSE_MUSIC")){
            //Do whatever you want. Ex. Pause
        }
        //Similarly this can be done for all actions
    }};

To register your Reciever add these lines in onCreate()要注册您的接收者,请在onCreate() 中添加这些行

            IntentFilter intentFilter=new IntentFilter();
            intentFilter.addAction("com.mypackage.ACTION_PAUSE_MUSIC");
            registerReceiver(receiver,intentFilter);

Note: You can add as many actions you want注意:您可以添加任意数量的操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM