当 activity 被销毁时服务停止

Service stops when activity is destroyed

关于这个问题,我在 Whosebug 上搜索了很多,但似乎没有任何效果。

我正在开发一个通过绑定到服务来播放音乐的音乐播放器。我有两个 activities.The 第一个 activity(称为 AllSongs)为我提供了 songs.When 的列表,我 select 一首它开始的歌曲另一个 activity(称为 SongUI),它通过绑定到服务来播放歌曲。

现在当我回到我的 AllSongs activity 音乐 stops.Now 当我再次 select 一首歌时,我的 SongUI activity 已启动,当我返回我的 AllSongs activity 时,音乐不会停止并在 background.I 我无法理解是什么导致了这个问题。我想我在某个地方做了一些愚蠢的事情,但无法弄清楚。我希望歌曲在后台播放,就像任何音乐播放器一样 does.Here 是代码。

所有歌曲activity:

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 activity:

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;
    }
}

}

我的服务class

 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);
}

我已经找到我哪里出错了。我在停止播放的 SongsUI activity 的 onDestroy 中调用了 unbindService(myConnection)。

第二次不是这种情况的原因是我在 onUnbind 方法中返回了 false。所以系统没有第二次调用 onBind 方法,随后 onUnbind 也没有被调用。因此播放也没有停止。