简体   繁体   English

Android Media Player应用程序服务

[英]Android Media Player App services

I am developing a media player app that has a bound service to an activity.It works fine when i press the home button or the app switcher and then come back to the app from the recent app, but as i press the back button the activity also ends the Music Service. 我正在开发一个对活动具有绑定服务的媒体播放器应用程序。当我按下主屏幕按钮或应用程序切换器,然后从最近的应用程序返回到该应用程序时,它工作正常,但是当我按下后退按钮时,该活动也结束了音乐服务。 Please guide me the exact steps that can solve these minor issues, so that i can give media controls to the app.My App has 2 main classes 请指导我解决这些小问题的确切步骤,以便我可以将媒体控件提供给该应用。我的应用有2个主要类别

  1. MyActivity 我的活动
  2. AudioService 音频服务

My code is given below. 我的代码如下。

AudioService.java AudioService.java

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

// -----------------------------------------Attributes--------------------------------------------------------
private ArrayList<File> songs;
private ArrayList<File> audio;
private MediaPlayer player;
private int songPosn;
private String name="";
private final IBinder musicBind = new AudioBinder();
private Uri trackUri;
private int NOTIFY_ID=1;
// -----------------------------------------------------------------------------------------------------------


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

    initMusicPlayer();


}

// to initialize the media class
public void initMusicPlayer(){
    //set player properties

    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<File> theSongs){
    songs=theSongs;
}

public void setSong(int songIndex){
    songPosn=songIndex;
}

public class AudioBinder extends Binder {

  AudioService getService() {
        return AudioService.this;
    }
}

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

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

}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    mp.reset();
    return false;
}


@Override
public void onPrepared(MediaPlayer mp) {
    //start playback
    mp.start();
showNotification();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId){
    songPosn = intent.getIntExtra("pos",0);
    audio=(ArrayList)intent.getParcelableArrayListExtra("songlist");
    name = intent.getStringExtra("name");
    Log.e("Service","name"+audio.get(0));
    Log.e("Service","position "+songPosn);

    return  START_STICKY;
}
public void playSong(){
    //play a song

    player.reset();


    Log.e("TRACH the URI",""+trackUri);
    trackUri =Uri.parse(audio.get(songPosn).toString());

    try{
        player.setDataSource(getApplicationContext(), trackUri);
    }
    catch(Exception e){
        Log.e("MUSIC SERVICE", "Error setting data source", e);
    }

    player.prepareAsync();
}

private void showNotification(){
    Intent notIntent = new Intent(this, MyActivity.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)
            .setTicker(name)
            .setOngoing(true)
            .setContentTitle("Playing")
            .setContentText(name);
    Notification not = builder.build();

    startForeground(NOTIFY_ID, not);
}

@Override
public void onDestroy()
{
    stopForeground(true);
}
}

MyActivity.java MyActivity.java

public class MyActivity extends Activity {

    // *****************************  Attributes Start ******************************************************
    private ArrayList<File> myfiles= new ArrayList<File>();
    private ListView listView;
    private ArrayAdapter<String> adapter ;
    private String name="";
    private int position;

    private AudioService musicSrv;
    private Intent playIntent;
    private boolean musicBound=false;

    // *****************************  Attributes End ******************************************************



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

        String toneslist[] ={"Airtel"
                ,"sherlock_theme"};

        listView = (ListView) findViewById(R.id.listView);
        adapter = new ArrayAdapter<String>(getApplication(),R.layout.list_item,R.id.list_textview,toneslist);
        listView.setAdapter(adapter);

        getMp3();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {

                name =adapter.getItem(pos);
                position =pos;

                Log.e("MAINACTIVITY (clickListener) pos =",""+position+"  name = "+name);

                musicSrv.setSong(position);
                musicSrv.playSong();

            }
        });
    }


    @Override
    protected void onStart() {
        super.onStart();
        if(playIntent==null){
            Log.e("MAINACTIVITY  pos =",""+position+"  name = "+name);
            playIntent = new Intent(this, AudioService.class).putExtra("pos",position).putExtra("songlist", myfiles).putExtra("name", name);
            bindService(playIntent, audioConnection, Context.BIND_AUTO_CREATE);
            startService(playIntent);

        }
    }

    private ServiceConnection audioConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
                AudioService.AudioBinder binder = (AudioService.AudioBinder)service;
            musicSrv = binder.getService();
            musicSrv.setList(myfiles);
            musicBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

            musicBound = false;
        }
    };



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private  void getMp3(){
        String s=(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)).toString();
        // s="content://media/external/audio/media";

        GetFiles(s);

    }

    private void GetFiles(String path) {

        File file = new File(path);
        File[] allfiles = file.listFiles();
        if (allfiles.length == 0) {

        } else {
            for (int i = 0; i < allfiles.length; i++)
            {
                Log.e("FFFFFFFFF", allfiles[i].getName().toString());
               myfiles.add(allfiles[i]);
            }
        }

    }

    @Override
    protected void onPause() {

        super.onPause();
    }

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

Try with this in your Activity: 在您的活动中尝试以下操作:

@Override
public void onDestroy(){
    if (!isChangingConfigurations()) stopService(new Intent (this, YourService.class));
    super.onDestroy();
}

@Override
public void onBackPressed(){
    if (mediaIsPlaying) moveTaskToBack(true);
    else super.onBackPressed();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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