Android Media Player应用服务

时间:2015-07-08 08:25:05

标签: java android service android-music-player

我正在开发一个媒体播放器应用程序,它具有对活动的绑定服务。当我按下主页按钮或应用程序切换器然后从最近的应用程序返回应用程序时工作正常,但是当我按下后面按钮活动也结束了音乐服务。请指导我可以解决这些小问题的确切步骤,以便我可以为应用程序提供媒体控制。我的应用程序有2个主要类

  1. MyActivity
  2. AudioService
  3. 我的代码如下。

    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

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

1 个答案:

答案 0 :(得分:0)

在您的活动中尝试使用此功能:

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