从通知中恢复活动

时间:2013-09-30 21:59:24

标签: android

我是android的新手,我需要一些帮助。

我正在做一个音乐播放器目标api 10.我有一个服务,它在背景中重现音乐,它绑定到一个显示图形再现的活动,如播放按钮,下一首歌等等。

在活动中我覆盖onKeyDown(int keycode,KeyEvent事件),所以当点击home或菜单按钮时,会创建一个通知。

我创建了这样的通知:

 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;
}

提前感谢。

1 个答案:

答案 0 :(得分:0)

实际上onBackPressed方法用于处理后退按钮。

但我建议你改变方法。由于无法保证您的活动获得任何消息(onSaveInstanceState除外),因此您最好不要依赖它。尝试使用服务的startForeground方法,您可以在其中定义通知图标,这对于长期运行的服务非常有帮助。