如何创建在被点击时播放音频文件的通知



我想显示一个通知,当用户点击它时,应该播放一个声音文件。

在Android Studio中,我已将文件test.mp3复制到文件夹appresraw中。通知由以下代码发出:

Resources resources = getResources();                                                 
Uri uri = new Uri.Builder()                                                           
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)                              
.authority(resources.getResourcePackageName(R.raw.test))                      
.appendPath(resources.getResourceTypeName(R.raw.test))                        
.appendPath(resources.getResourceEntryName(R.raw.test))                       
.build();                                                                     
                
Intent playSoundIntent = new Intent();                                                
playSoundIntent.setAction(android.content.Intent.ACTION_VIEW);                        
playSoundIntent.setDataAndType(uri, "audio/*");                                       
                
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,                      
playSoundIntent, 0);                                                          
                
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,             
MainActivity.notificationChannelId)                                           
.setSmallIcon(android.R.drawable.ic_media_play)                               
.setContentTitle(getResources().getString(R.string.app_name))                 
.setContentText("Tap to play sound!")                                         
.setContentIntent(pendingIntent)                                              
.setPriority(NotificationCompat.PRIORITY_DEFAULT)                             
.setAutoCancel(true);                                                         
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(12345678, builder.build());                                

它没有按预期工作。会显示通知,如果我点击它,它就会消失(因为setAutoCancel(true)(。但我听不到任何声音。为什么?

如何调试它?

非常感谢!

我通过创建这样的意图来管理它:

Intent playSoundIntent = new Intent(this, PlaySoundActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, playSoundIntent, 0);

并添加活动:

public class PlaySoundActivity extends AppCompatActivity
{
private static MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mediaPlayer = MediaPlayer.create(this, R.raw.test);
mediaPlayer.start();
}
@Override
public void onStop()
{
super.onStop();
mediaPlayer.stop();
mediaPlayer.release();
}
}

尽管这是有效的,但我仍然对为什么前一种方法不起作用感兴趣。我见过很多类似的代码片段。我仍然想知道如何调试前一种方法来理解错误。有人能帮我吗?

最新更新