我是 android 新手,我需要一些帮助。
我正在做一个音乐播放器目标 api 10。我有一个在后台再现音乐的服务,它绑定到一个显示图形再现的活动,比如播放按钮、下一首歌等等。
在活动中,我覆盖了 onKeyDown(int keycode, KeyEvent event),因此当单击主页或菜单按钮时,会创建一个通知。
我创建了这样的通知:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.play_notify)
.setContentTitle(songsList.get(currentSongIndex))
.setContentText("Hello World!");
mBuilder.setAutoCancel(true);
Intent resultIntent = new Intent(this, PlayerActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultPendingIntent =PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
问题是我也想在按下后退按钮时执行此操作(不仅是菜单和主页按钮),但它不起作用......它强制关闭应用程序,因为活动中的 nullPointerExeption 绑定到服务。
我不得不提到通知是在后按时创建的,问题是当我单击通知返回活动时......
听听全部方法:
@Override
public boolean onKeyDown(int keycode, KeyEvent event ) {
if(keycode == KeyEvent.KEYCODE_MENU || keycode == KeyEvent.KEYCODE_HOME || keycode==KeyEvent.KEYCODE_BACK){
if (mServ.isPlaying()){
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.play_notify)
.setContentTitle(songsList.get(currentSongIndex))
.setContentText("Hello World!");
mBuilder.setAutoCancel(true);
Intent resultIntent = new Intent(this, PlayerActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent resultPendingIntent =PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
if (keycode == KeyEvent.KEYCODE_BACK){
super.onBackPressed () ;
}
else
moveTaskToBack(true);
}
return super.onKeyDown(keycode,event);
}
return false;
}
提前致谢。