我正在制作一个音乐应用程序,它在播放音频时显示通知。单击时,此通知将通过 Intent 打开主 (UI) Activity 。
虽然这应该是一个非常简单的过程,但出于某种原因,无论我做什么,当按下通知时,主要 Activity 总是会被破坏。我尝试过 singleTop、singleTask(既作为 Intent 标志又作为 list 值)、保存实例状态包、onNewIntent,基本上任何接近我能找到的解决方案的东西。但 Activity 总是被破坏。我只能通过getIntent获取 Intent 。
主要 Activity :https://pastebin.com/32uuK33E
音频服务:https://pastebin.com/ShiUfBMc
list :https://pastebin.com/kPp7RSYK
<小时/>因为“指向pastebin的链接必须附有代码”
这就是 Intent (我已经尝试了相关标志的所有组合,所以我真的怀疑这就是问题所在)
// creates an intent which opens the application when the notification is pressed
private PendingIntent getPendingIntent(Context context) {
Intent intent = getIntent(this);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntent(intent);
return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
}
// returns an intent which resumes the Main Activity and passes various song information
private Intent getIntent(Context context) {
int duration = player != null ? player.getDuration() : 0;
boolean playing = player != null && player.isPlaying();
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.putExtra(MediaPlayerContract.INTENT_EXTRA_SONG_INFO, getSongInfo());
intent.putExtra(MediaPlayerContract.INTENT_EXTRA_POS, currentQueuePos);
intent.putExtra(MediaPlayerContract.INTENT_EXTRA_DURATION, duration);
intent.putExtra(MediaPlayerContract.INTENT_EXTRA_IS_PLAYING, playing);
return intent;
}
这是我尝试读取数据的地方
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.e(LOG_TAG, "flag got intent");
String[] info = intent.getStringArrayExtra(MediaPlayerContract.INTENT_EXTRA_SONG_INFO);
int pos = intent.getIntExtra(MediaPlayerContract.INTENT_EXTRA_POS, 0);
int duration = intent.getIntExtra(MediaPlayerContract.INTENT_EXTRA_DURATION, 0);
unpackageSongInfo(info);
currentQueuePos = pos;
seekBar.setMax(duration);
setIntent(intent);
}
最佳答案
尝试删除标志:Intent.FLAG_ACTIVITY_CLEAR_TOP
并添加下一个:Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
关于java - 通知总是创建新的 Activity 而不是恢复以前的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52249563/