2015-07-08 3 views
0

Я разрабатываю приложение для медиаплеера, которое имеет связанный сервис с активностью. Он отлично работает, когда я нажимаю кнопку «Главная» или переключатель приложения, а затем возвращаюсь к приложению из недавнего приложения, но когда я нажимаю кнопку «Назад», действие также заканчивается Службой музыки. Пожалуйста, руководство мне точные шаги, которые могут решить эти незначительные проблемы, так что я могу дать управления мультимедиа в app.My App имеет 2 основных классовПриложение для Android-плееров Android

  1. MyActivity
  2. аудиообслуживание

Мой код нижеприведенный.

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

Вы должны установить службу в качестве переднего плана службы, чтобы он мог жить, когда приложение разрушается. – LightYearsBehind

+0

это потому, что вы называете 'stopService (playIntent);' in 'onDestroy' – pskink

+0

может ли сказать мне, что я должен сделать, чтобы все исправить? – Abad

ответ

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(); 
} 
Смежные вопросы