2016-10-06 40 views
0

我試圖調用此方法,但它是沒有得到調用onServiceConnected並沒有叫

ServiceConnection musicConnection = new ServiceConnection(){ onServiceConnected(ComponentName name, IBinder service) 

由於這我收到以下錯誤。 當它在片段上時它工作的很好,但是當我嘗試在AppCompatActivity上運行它時,它不工作。

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.kpgames.testmusicplayer.MusicService.setSong(int)' on a null object reference 
---------- 

     java.lang.IllegalStateException: Could not execute method of the activity 
                       at android.view.View$1.onClick(View.java:4023) 
                       at android.view.View.performClick(View.java:4783) 
                       at android.view.View$PerformClick.run(View.java:19887) 
                       at android.os.Handler.handleCallback(Handler.java:739) 
                       at android.os.Handler.dispatchMessage(Handler.java:95) 
                       at android.os.Looper.loop(Looper.java:135) 
                       at android.app.ActivityThread.main(ActivityThread.java:5290) 
                       at java.lang.reflect.Method.invoke(Native Method) 
                       at java.lang.reflect.Method.invoke(Method.java:372) 
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908) 
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703) 
                       Caused by: java.lang.reflect.InvocationTargetException 
                       at java.lang.reflect.Method.invoke(Native Method) 
                       at java.lang.reflect.Method.invoke(Method.java:372) 
                       at android.view.View$1.onClick(View.java:4018) 
                       at android.view.View.performClick(View.java:4783)  
                       at android.view.View$PerformClick.run(View.java:19887)  
                       at android.os.Handler.handleCallback(Handler.java:739)  
                       at android.os.Handler.dispatchMessage(Handler.java:95)  
                       at android.os.Looper.loop(Looper.java:135)  
                       at android.app.ActivityThread.main(ActivityThread.java:5290)  
                       at java.lang.reflect.Method.invoke(Native Method)  
                       at java.lang.reflect.Method.invoke(Method.java:372)  
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)  
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)  
                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.kpgames.testmusicplayer.MusicService.setSong(int)' on a null object reference 
                       at com.kpgames.testmusicplayer.MainActivity.songPicked(MainActivity.java:90) 
                       at java.lang.reflect.Method.invoke(Native Method)  
                       at java.lang.reflect.Method.invoke(Method.java:372)  
                       at android.view.View$1.onClick(View.java:4018)  
                       at android.view.View.performClick(View.java:4783)  
                       at android.view.View$PerformClick.run(View.java:19887)  
                       at android.os.Handler.handleCallback(Handler.java:739)  
                       at android.os.Handler.dispatchMessage(Handler.java:95)  
                       at android.os.Looper.loop(Looper.java:135)  
                       at android.app.ActivityThread.main(ActivityThread.java:5290)  
                       at java.lang.reflect.Method.invoke(Native Method)  
                       at java.lang.reflect.Method.invoke(Method.java:372)  
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:908)  
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:703)  

MainActivity.java

public class MainActivity extends AppCompatActivity implements MediaPlayerControl{ 
private ArrayList<Song> songList; 
private ListView songView; 
private MusicController controller; 

private MusicService musicSrv; 
private Intent playIntent; 
private boolean musicBound=false; 
private boolean paused=false, playbackPaused=false; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 



    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    songView = (ListView)findViewById(R.id.song_list); 
    songList = new ArrayList<Song>(); 
    getSongList(); 
    Collections.sort(songList, new Comparator<Song>(){ 
     public int compare(Song a, Song b){ 
      return a.getTitle().compareTo(b.getTitle()); 
     } 
    }); 

    SongAdapter songAdt = new SongAdapter(this, songList); 
    songView.setAdapter(songAdt); 
    setController(); 


} 


//connect to the service 
private ServiceConnection musicConnection = new ServiceConnection(){ 

    @Override 
    public void onServiceConnected(ComponentName name, IBinder service) { 
     MusicBinder binder = (MusicBinder)service; 
     //get service 
     musicSrv = binder.getService(); 
     //pass list 
     musicSrv.setList(songList); 
     musicBound = true; 
    } 

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

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


public void songPicked(View view){ 
    musicSrv.setSong(Integer.parseInt(view.getTag().toString())); 
    musicSrv.playSong(); 
    if(playbackPaused){ 
     setController(); 
     playbackPaused=false; 
    } 
    controller.show(0); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case R.id.action_shuffle: 
      musicSrv.setShuffle(); 
      break; 
     case R.id.action_end: 
      stopService(playIntent); 
      musicSrv=null; 
      System.exit(0); 
      break; 

    } 
    return super.onOptionsItemSelected(item); 
} 

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

public void getSongList() { 
    ContentResolver musicResolver = getContentResolver(); 
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; 
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null); 

    if(musicCursor!=null && musicCursor.moveToFirst()){ 
     //get columns 
     int titleColumn = musicCursor.getColumnIndex 
       (android.provider.MediaStore.Audio.Media.TITLE); 
     int idColumn = musicCursor.getColumnIndex 
       (android.provider.MediaStore.Audio.Media._ID); 
     int artistColumn = musicCursor.getColumnIndex 
       (android.provider.MediaStore.Audio.Media.ARTIST); 
     //add songs to list 
     do { 
      long thisId = musicCursor.getLong(idColumn); 
      String thisTitle = musicCursor.getString(titleColumn); 
      String thisArtist = musicCursor.getString(artistColumn); 
      songList.add(new Song(thisId, thisTitle, thisArtist)); 
     } 
     while (musicCursor.moveToNext()); 
    } 
} 

private void setController(){ 
    controller = new MusicController(this); 
    controller.setPrevNextListeners(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      playNext(); 
     } 
    }, new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      playPrev(); 
     } 
    }); 
    controller.setMediaPlayer(this); 
    controller.setAnchorView(findViewById(R.id.song_list)); 
    controller.setEnabled(true); 
} 

private void playNext(){ 
    musicSrv.playNext(); 
    if(playbackPaused){ 
     setController(); 
     playbackPaused=false; 
    } 
    controller.show(0); 
} 

private void playPrev(){ 
    musicSrv.playPrev(); 
    if(playbackPaused){ 
     setController(); 
     playbackPaused=false; 
    } 
    controller.show(0); 
} 

@Override 
public void start() { 
    musicSrv.go(); 
} 

@Override 
public void pause() { 
    playbackPaused=true; 
    musicSrv.pausePlayer(); 
} 

@Override 
public int getDuration() { 
    if(musicSrv!=null && musicBound && musicSrv.isPng()) 
    return musicSrv.getDur(); 
    else return 0; 
} 

@Override 
public int getCurrentPosition() { 
    if(musicSrv!=null && musicBound && musicSrv.isPng()) 
    return musicSrv.getPosn(); 
    else return 0; 
} 

@Override 
protected void onPause(){ 
    super.onPause(); 
    paused=true; 
} 
@Override 
protected void onResume(){ 
    super.onResume(); 
    if(paused){ 
     setController(); 
     paused=false; 
    } 
} 
@Override 
protected void onStop() { 
    controller.hide(); 
    super.onStop(); 
} 

@Override 
public void seekTo(int pos) { 
    musicSrv.seek(pos); 
} 


@Override 
public boolean isPlaying() { 
    if(musicSrv!=null && musicBound) 
    return musicSrv.isPng(); 
    return false; 
} 

@Override 
public int getBufferPercentage() { 
    return 0; 
} 

@Override 
public boolean canPause() { 
    return true; 
} 

@Override 
public boolean canSeekBackward() { 
    return true; 
} 

@Override 
public boolean canSeekForward() { 
    return true; 
} 

@Override 
public int getAudioSessionId() { 
    return 0; 
} 

}

這是服務代碼

public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { 


//media player 
private MediaPlayer player; 
//song list 
private ArrayList<Song> songs; 
//current position 
private int songPosn; 
private final IBinder musicBind = new MusicBinder(); 
private String songTitle = ""; 
private static final int NOTIFY_ID = 1; 
private boolean shuffle = false; 
private Random rand; 


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

@Override 
public boolean onUnbind(Intent intent) { 
    player.stop(); 
    player.release(); 
    return false; 
} 

public void onCreate() { 
    //create the service 
    super.onCreate(); 
//initialize position 
    songPosn = 0; 
//create player 
    player = new MediaPlayer(); 
    initMusicPlayer(); 
    rand = new Random(); 

} 

public void initMusicPlayer() { 
    player.setWakeMode(getApplicationContext(), 
      PowerManager.PARTIAL_WAKE_LOCK); 
    player.setAudioStreamType(AudioManager.STREAM_MUSIC); 
    player.setOnPreparedListener(this); 
    player.setOnCompletionListener(this); 
    player.setOnErrorListener(this); 

} 

public void setList(ArrayList<Song> theSongs) { 
    songs = theSongs; 
} 

public class MusicBinder extends Binder { 
    MusicService getService() { 
     return MusicService.this; 
    } 
} 

謝謝!

+0

我有同樣的問題。 – Tama

回答

0

Android爲每個服務調用一次onBind()方法。如果你以後綁定/取消綁定,方法.onRebind()被稱爲

+0

這是我綁定服務的唯一方法。你能幫我怎麼做。 –