我想显示一个通知,当用户点击它时,应该播放一个声音文件。
在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();
}
}
尽管此方法可行,但我仍然对为什么前一种方法不起作用感兴趣。我已经看到很多类似的代码片段。而且我仍然想知道如何调试以前的方法来理解错误。有谁能够帮助我?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句