为什么我得到一个null.p.ex。在startForegrund上?

dii*_*iz_ 4 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在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)
Run Code Online (Sandbox Code Playgroud)

...

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)
Run Code Online (Sandbox Code Playgroud)

谢谢!

Yur*_*ets 6

解决方案很简单:

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

    mediaPlayerService =  new MediaPlayerService();
Run Code Online (Sandbox Code Playgroud)