为什么我得到null.p.ex.在startForegrund?

时间:2014-02-12 17:36:56

标签: android media-player

我想制作一个通知来控制我的音乐播放器,所以我想开始一个前台服务。

我的代码:

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
protected void onStop(){
    super.onStop();
    System.out.println("Stop");
    Toast.makeText(this,"Stopped",Toast.LENGTH_SHORT).show();
    if(play_media.isPlaying()){
        PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(getApplicationContext(), MainActivity.class),
                PendingIntent.FLAG_UPDATE_CURRENT);
        Notification notification = new Notification.Builder(mContext)
                .setContentTitle("Playing")
                .setContentText("playing a song")
                .setSmallIcon(R.drawable.ic_play)
                .setLargeIcon(list.get(mDrawerList.getCheckedItemPosition()).getAlbum_Art())
                .setContentIntent(pi)
                .build();

        mediaPlayerService =  new MediaPlayerService();
 322:       mediaPlayerService.startForeground(NOTIFICATION_ID,notification);
    }
}

在startForeground上遇到异常:

02-12 18:06:08.935    4405-4405/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.Driiinx.musicslide, PID: 4405
java.lang.RuntimeException: Unable to stop activity {...com.Driiinx.musicslide.MainActivity}: java.lang.NullPointerException: class name is null
at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3188)

...

Caused by: java.lang.NullPointerException: class name is null
        at android.content.ComponentName.<init>(ComponentName.java:63)
        at android.app.Service.startForeground(Service.java:643)
        at com.Driiinx.musicslide.MainActivity.onStop(MainActivity.java:322)

谢谢!

1 个答案:

答案 0 :(得分:5)

解决方案很简单:

  • 明确启动服务(例如在活动中)

    Intent serviceIntent = new Intent(this, TheService.class);  
    startService(serviceIntent);
    
  • 您应该在服务onCreate()
  • 致电startForeground(...)

    Notification notification = ...;
    startForeground(101, notification);
    

导致您的问题的错误代码是服务的实例化:

    mediaPlayerService =  new MediaPlayerService();