在Android服务创建中获取NullPointerException

时间:2015-01-20 17:55:29

标签: android android-service

我正在尝试制作一个简单的服务来播放mp3文件。下面是我的服务类代码。

public class MyService extends Service {

    private IBinder iBinder = new LocalBinder();
    private ArrayList<Song> songsList;
    private MediaPlayer player;

    @Override
    public void onCreate() {
        player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.reset();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return iBinder;
    }

    public class LocalBinder extends Binder{
        public MyService getService() {
            return MyService.this;
        }
    }

    public void setSongsList(ArrayList<Song> songsList) {
        this.songsList = songsList;
    }

    public void playSong(Song song) {
        try {
            player.setDataSource(getApplicationContext(), Uri.parse(song.getPath()));
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

这是我的Activity类。

public class MyActivity extends Activity {

    private MyService myService;
    private boolean mBound;
    private ArrayList<Song> songsList = new ArrayList<Song>();
    private Uri musicUri;
    private ContentResolver musicResolver;
    private int count;

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mBound = true;
            MyService.LocalBinder binder = (MyService.LocalBinder)iBinder;
            myService = binder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBound = false;
            //myService = null;
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        Intent i = new Intent(this, MyService.class);
        bindService(i, serviceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mBound) {
            myService.unbindService(serviceConnection);
            mBound = false;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        musicResolver = getContentResolver();
        prepareListOfSongsAndAlbumMap();
        /*for(Song s: songsList) {
            Log.i("Song", s.getTitle());
        }*/
        if(myService == null) {
            Log.i("NULL SERVICE", "NULL");
        }
        myService.setSongsList(songsList);
        myService.playSong(songsList.get(3));

    }

    private void prepareListOfSongsAndAlbumMap() {
        this.musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        String[] projection = null;
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
        String selectionMimeType = MediaStore.Audio.Media.IS_MUSIC + " !=0";

        Cursor musicCursor = musicResolver.query(musicUri, projection, selectionMimeType, null, sortOrder);
        count = musicCursor.getCount();
        if(musicCursor != null && musicCursor.moveToFirst()) {
            do {
                String path = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String title = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String album = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String artist = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int artistId = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                int albumId = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
                int trackId = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.TRACK));
                long duration = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.DURATION));

                Uri sArtworkUri = Uri
                        .parse("content://media/external/audio/albumart");
                Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);

                Song song = new Song(path, title, album, artist, albumId, trackId, duration, albumArtUri.toString(), artistId);
                songsList.add(song);

            }while(musicCursor.moveToNext());
        }
        musicCursor.close();
    }
}

当我尝试运行此代码时,我收到NullPointerException,myService未被创建。我无法弄清楚我在哪里弄错了。

以下是日志详细信息。

  java.lang.RuntimeException: Unable to start activity ComponentInfo{music.skumar.com.servicetest/music.skumar.com.servicetest.MyActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2268)
        at android.app.ActivityThread.access$600(ActivityThread.java:148)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1263)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5162)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        atcom.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572)
        at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at music.skumar.com.servicetest.MyActivity.onCreate(MyActivity.java:76)
        at android.app.Activity.performCreate(Activity.java:5135)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at com.lbe.security.service.core.client.b.x.callActivityOnCreate(Unknown Source)
  atandroid.app.ActivityThread.performLaunchActivity(ActivityThread.java:2182) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2268)
            at android.app.ActivityThread.access$600(ActivityThread.java:148)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1263)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5162)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572)
            at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

至少在您的活动首次创建时,myService中的null将为onCreate()。您不仅要在bindService()之前调用onStart()(在onCreate()之后发生),而且bindService()是异步的。在调用myService之前,请勿尝试使用onServiceConnected()