活动被销毁时服务停止

时间:2015-11-20 17:13:07

标签: android android-activity android-service android-service-binding

我在stackoverflow上搜索了很多关于这个问题但似乎没什么用。

我正在开发一种音乐播放器,它通过绑定服务来播放音乐。我有两个活动。第一个活动(称为 AllSongs )为我提供了歌曲列表。当我选择一首歌时,它开始另一个活动(称为 SongUI )通过绑定到服务来播放歌曲。

现在当我回到我的 AllSongs 活动时,音乐会停止。现在当我再次选择一首歌时,我的 SongUI 活动开始了,当我回到我的 AllSongs 活动,音乐不会停止并在后台播放。我无法理解导致此问题的原因。我想我在某个地方做些傻事但是我无法弄明白。我想要在背景中播放与任何音乐播放器相同的歌曲。这就是代码。

AllSongs活动:

public class AllSongs extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.allsongs_activity);

    getSongList();
    from = new String[]{MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.DURATION};
    to = new int[]{R.id.title_entry,R.id.artist_entry,R.id.duration_entry};
    listView = (ListView) findViewById(R.id.listView);
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.singlesong,myCursor,from,to,SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent songUIIntent = new Intent(getApplicationContext(),SongUI.class);             
            songUIIntent.putExtra("position",id);
            startActivity(songUIIntent);
        }
    });
}

private void getSongList() {

    ContentResolver myContentResolver = getContentResolver();
    myCursor = myContentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,null);
    if(myCursor!=null && myCursor.moveToFirst()) {
        int titleColumn = myCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);           
        int idColumn = myCursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);            
        int artistColumn = myCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);          
        long albumID = myCursor.getLong(myCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));         

        do {
            long ID = myCursor.getLong(idColumn);              
            String title = myCursor.getString(titleColumn);             
            String artist = myCursor.getString(artistColumn);              
            songList.add(new currentSong(ID,title,artist));
        }while (myCursor.moveToNext());
    }
}

@Override
protected void onDestroy() {
        super.onDestroy();
    }
}

SongUI活动:

public class SongUI extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.song_ui);
    button = (Button) findViewById(R.id.play);
    isBound = false;       
    Intent receivedIntent = getIntent();
    position = receivedIntent.getLongExtra("position",0);       
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main,menu);
    return super.onCreateOptionsMenu(menu);
}

public void playAudio(View view) {     
    Intent objIntent = new Intent(this,MyService.class);   
    if(!isBound)
    {          
        objIntent.putExtra("position", position);
        startService(objIntent);          
        isBound=true;
        button.setBackgroundResource(R.drawable.play);           
        bindService(objIntent, myConnection, Context.BIND_AUTO_CREATE);           
    }
    else
    {          
        myServiceObject.pauseAudio();    
        button.setBackgroundResource(R.drawable.play);
        isBound=false;         
        unbindService(myConnection);        
    }
}

public void stopAudio(View view) {     
    Intent objIntent = new Intent(this,MyService.class);    
    if(isBound)
    {         
        isBound=false;           
        unbindService(myConnection);           
        stopService(objIntent);          

    }
    else {      
        stopService(objIntent);           
    }
    button.setBackgroundResource(R.drawable.play);
}

private ServiceConnection myConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className,
                                   IBinder service) {            
        myServiceObject = ((MusicBinder) service).getService();         
        isBound = true;
    }

    public void onServiceDisconnected(ComponentName arg0) {           
        isBound = false;
    }
};

@Override
protected void onDestroy() {       
    super.onDestroy();      
    if (isBound) {           
       unbindService(myConnection);          
        isBound = false;
    }
}

}

MyService类

 public class MyService extends Service {

@Override
public void onCreate() {
    super.onCreate();      
    player = new MediaPlayer();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "on startCommand is called");
    long id = intent.getLongExtra("position",0);
    Uri contentUri = ContentUris.withAppendedId(
            android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
    Log.d(TAG, "Service is Started");
    player = MediaPlayer.create(this,contentUri);      
    player.start();

    Intent notIntent = new Intent(this, SongUI.class);
    notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendInt = PendingIntent.getActivity(this, 0,
            notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder builder = new Notification.Builder(this);

    builder.setContentIntent(pendInt)
            .setSmallIcon(R.drawable.play)
            .setTicker(songTitle)
            .setOngoing(true)
            .setContentTitle("Playing")
            .setContentText(songTitle);
    Notification notification = builder.build();
    startForeground(NOTIFY_ID, notification);

    return Service.START_STICKY;

}
@Override
public IBinder onBind(Intent intent) {
    Log.d(TAG, "on Bind is called");
    return myBinder;
}
@Override
public boolean onUnbind(Intent intent){
    Log.d(TAG,"onUnbind is called");
    player.stop();
    player.release();
    return false;
}

public class MusicBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}
 public void pauseAudio() {      
    if(player.isPlaying()) {         
        player.pause();
    }
}
  @Override
public void onDestroy() {
    Log.d(TAG,"on destroy is called");
    stopForeground(true);
}

1 个答案:

答案 0 :(得分:1)

我已经弄清楚我哪里出错了。我在我的SongsUI活动的onDestroy中调用了unbindService(myConnection),该活动正在停止播放。

而第二轮的情况并非如此,我在onUnbind方法中返回false。所以系统第二次没有调用onBind方法,随后onUnbind也没有被调用。因此播放也没有停止。