服务对象未初始化/未调用onServiceCreated

时间:2016-07-01 12:51:29

标签: android service

我正在制作音乐播放器应用。当我单击SongsFragment.java中的列表项时,它会向PlayerActivity.java发送具有歌曲位置的意图。 musicSrv始终为null。我在google上寻找Activity lifecyle,并发现它与此有关。因为我是初学者所以不能适用。

SongsFragment:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    //musicSrv.setSong(position);
    //musicSrv.playSong();
    Intent intent = new Intent(getContext(), PlayerActivity.class);
    intent.putExtra("pos", position);
    startActivity(intent);
}

在PlayerActivity.java中:

public class PlayerActivity extends AppCompatActivity {
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private static final String POS = "pos";
private int passedPos;



protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras();
    passedPos = extras.getInt("pos",0);
    musicSrv.setSong(passedPos);
    musicSrv.playSong();

    setContentView(R.layout.activity_player);
}


ServiceConnection musicConnection = new ServiceConnection(){

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
        //Get service
        musicSrv = binder.getService();
        //Pass list
        ArrayList<Song> songs = ((DataFetcher)getApplicationContext()).songList;
        musicSrv.setList(songs);
        musicBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        musicBound = false;
    }
};

@Override
public void onStart() {
    super.onStart();
    if(playIntent==null) {
        playIntent = new Intent(this,(Class)MusicService.class);
        bindService(playIntent,musicConnection, Context.BIND_AUTO_CREATE);
        startService(playIntent);
    }
}

@Override
public void onDestroy() {
    stopService(playIntent);
    musicSrv=null;
    super.onDestroy();
}

}

错误:我收到“Attempt to invoke virtual method 'void services.MusicService.setSong(int)' on a null object reference

1 个答案:

答案 0 :(得分:1)

首先,在onCreate()之前调用onStart()musicSrvnull,因为您尚未调用bindService()

其次,bindService()本身是异步的。在调用onServiceConnected()方法之前的某个时间。

在为该字段指定值之前,您无法使用musicSrv,而且最早在onServiceConnected()内部之前就无法使用{<1}}。

因此,在您知道musicSrv应该准备就绪后,将与onServiceConnected()相关的来电移至musicSrv或稍后的事件。

此外,请勿直接致电bindService(),因为这会让您在使用此活动进行配置更改时遇到麻烦。使用bindService()对象(例如unbindService())致电Application(以及之后的getApplicationContext().bindService())。