android - 如何创建在被点击时播放音频文件的通知?
问题描述
我想显示一个通知,当用户点击它时,应该播放一个声音文件。
在 Android Studio 中,我已将文件复制到文件test.mp3
夹app\res\raw
中。此代码发出通知:
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();
}
}
虽然这可行,但我仍然对为什么前一种方法不起作用感兴趣。我见过很多这样的代码片段。我仍然想知道如何调试前一种方法来理解错误。有谁能够帮我?
推荐阅读
- c# - 在 C# 控制台应用程序中删除控制台键入的文本
- python - 有没有办法处理 Window 的命令行错误?
- proftpd - 如何在 ProFTPD 上实现没有表的静态/固定 SQLGroupInfo?
- javascript - 在异步调用和共享变量之间
- javascript - 使用 javascript 对 HTML 表的项目进行分类
- gcc - 这是 GCC 错误还是我做错了什么?
- mysql - 分组和排序计数 desc 花费时间
- windows-10-universal - 错误:我的新类的当前上下文中不存在名称“FindName”
- excel - 在 Excel 中如何处理某些数组和数组函数;特别是数组处理对调用函数的依赖性
- c - 函数调用后输出不同的值?