简体   繁体   中英

Playing song when pressed back button

I am trying to play song in service but when I press the back button it stop playing the song so i override the onbackpress method but when i do that it directly brings me to the home screen .I am displaying multiple song category in different fragments and passing the arraylist and position via interface .This part is working fine but how can i play song when back button is pressed ,I tried to override the onpause method also but getting some error .What is the correct way to achieve this .here is my play method .

  @Override
public void onFragmentInteraction(ArrayList<Songfileinfo> songarr, int position) {
    playAudio(songarr, position);
    Log.v(""+songarr.size(),"I GOT THE SIZE");
}


private void playAudio(ArrayList<Songfileinfo> arrayList, int audioIndex) {
    //Check is service is active
    if (!serviceBound) {
        //Store Serializable audioList to SharedPreferences
        StorageUtil storage = new StorageUtil(getApplicationContext());
        storage.storeAudio(arrayList);
        storage.storeAudioIndex(audioIndex);

        Intent playerIntent = new Intent(this, MediaPlayerService.class);
        startService(playerIntent);
        bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    } else {
        //Store the new audioIndex to SharedPreferences
        StorageUtil storage = new StorageUtil(getApplicationContext());
        storage.storeAudio(arrayList);
        storage.storeAudioIndex(audioIndex);

        //Service is active
        //Send a broadcast to the service -> PLAY_NEW_AUDIO
        Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
        sendBroadcast(broadcastIntent);
    }
}

when i override the backpress methor it play the song .But from any fragment it brings me to the home screen

You have to make the service foreground when playing. That way the service wont be destroyed on closing activity. And remove the service from foreground when not playing any song. You dont need to override back button.

Your Service is bound to your Activity. Read here: https://developer.android.com/guide/components/bound-services.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM