当我按下主页按钮或后退按钮或锁定屏幕时,如何在后台运行媒体播放器

时间:2014-05-26 11:06:58

标签: android service android-mediaplayer

当我点击列表项时,我调用下一个活动并从哈希地图获取URL并将其分配给玩家活动现在我希望媒体播放器在后台运行如何可能?

Surah类从Fragment扩展

SurahlistView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {

                Play_SuraData = data.get(position);

                Intent i =new Intent(getActivity(), Player.class);

                i.putExtra("PlayUrl", "one");

                startActivity(i);

            }
        });     

Player.java

package com.example.quranpak;

import java.io.IOException;

import com.s3.helpers.DownloadImageTask;
import com.s3.helpers.ImagesCache;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.VideoView;

public class Player extends Activity implements OnPreparedListener,MediaController.MediaPlayerControl{

//  VideoView Video_Player;
//
//  DisplayMetrics dm;

//  SurfaceView sur_View;

    ImageView Player_img;

    ProgressBar Player_img_progress;

    MediaController media_Controller;

    MediaPlayer mplayer;

    ProgressDialog pDialog;

    private String Path, FrmDownload_Qariname, FrmDownload_Suraname, FrmFavourites_Qariname, FrmFavourites_Suraname;

    ImagesCache cache;

    Bitmap bitmap;

    String Key;

    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.player);

         cache = ImagesCache.getInstance();

        // Create a progressbar
        pDialog = new ProgressDialog(Player.this);

        // Set progressbar title
        pDialog.setTitle("Audio Streaming");

        // Set progressbar message
        pDialog.setMessage("Buffering...");

        pDialog.setIndeterminate(false);

        pDialog.setCancelable(false);

        // Show progressbar
        pDialog.show();

        Player_img = (ImageView) findViewById(R.id.Player_img);

        Player_img_progress = (ProgressBar) findViewById(R.id.Player_img_progress);

        Key = getIntent().getExtras().getString("PlayUrl");

        mplayer = new MediaPlayer();

        media_Controller = new MediaController(this);

        try {

            if(Key.equals("one"))
            {
                bitmap = cache.getImageFromWarehouse(SurahActivity.Play_SuraData.get("qari_image"));

                Path = SurahActivity.Play_SuraData.get("download_url");

                FrmDownload_Qariname = SurahActivity.Play_SuraData.get("qari_name");

                FrmDownload_Suraname = SurahActivity.Play_SuraData.get("sura_name");
            }
            else
            {
                bitmap = cache.getImageFromWarehouse(FavouriteActivity.Play_FavouriteData.get("qari_image"));

                Path = FavouriteActivity.Play_FavouriteData.get("url");

                FrmDownload_Qariname = FavouriteActivity.Play_FavouriteData.get("qari_name");

                FrmDownload_Suraname = FavouriteActivity.Play_FavouriteData.get("name");
            }

            mplayer.setDataSource(Path);

            mplayer.prepare();

            mplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

            mplayer.setLooping(true);

            mplayer.start();
        } 

        catch (IOException e) 
        {

            e.printStackTrace();
        }


        mplayer.setOnPreparedListener(this);


        if(bitmap != null)
        {
            Player_img_progress.setVisibility(View.GONE);

            Player_img.setImageBitmap(bitmap);
        }
        else
        {
            Player_img_progress.setVisibility(View.VISIBLE);

            Player_img.setImageBitmap(null);

            DownloadImageTask downloadImageTask = new DownloadImageTask(cache, Player_img, 300, 300);

            downloadImageTask.execute(SurahActivity.Play_SuraData.get("qari_image"));
        }

        ((TextView)findViewById(R.id.Player_Suraname)).setText(FrmDownload_Suraname);

        ((TextView)findViewById(R.id.Player_Qariname)).setText("By " + FrmDownload_Qariname);

    }


    @Override
    protected void onResume() {

        mplayer.start();
         super.onResume();


    }



    @Override
    public void onPrepared(MediaPlayer mp)
    {
        media_Controller.setMediaPlayer(this);

        media_Controller.setAnchorView(findViewById(R.id.main_audio_view));

        handler.post(new Runnable() 
        {
          public void run() 
          {
              pDialog.dismiss();

              media_Controller.setEnabled(true);

              media_Controller.show();

          }
        });
      }




     @Override
    protected void onDestroy() {
        super.onDestroy();

        media_Controller.hide();
        mplayer.stop();
//      mplayer.release();

    }



//   @Override
//  public void onBackPressed() {
//       
//      super.onBackPressed();
//  
//      getFragmentManager().popBackStack();
//  }

//  @Override
//    protected void onStop() {
//      super.onStop();
//      media_Controller.hide();
//      mplayer.stop();
//      mplayer.release();
//    }

      @Override
      public boolean onTouchEvent(MotionEvent event) 
      {
        //the MediaController will hide after 3 seconds - tap the screen to make it appear again
          media_Controller.show();
        return false;

      }


    @Override
    public boolean canPause() 
    {

        return true;
    }

    @Override
    public boolean canSeekBackward()
    {

        return true;
    }

    @Override
    public boolean canSeekForward()
    {
        return true;
    }

    @Override
    public int getAudioSessionId() 
    {
        return 0;
    }

    @Override
    public int getBufferPercentage()
    {

        return 0;
    }

    @Override
    public int getCurrentPosition() 
    {

        return mplayer.getCurrentPosition();
    }

    @Override
    public int getDuration() 
    {

        return mplayer.getDuration();
    }

    @Override
    public boolean isPlaying() 
    {

        return mplayer.isPlaying();
    }

    @Override
    public void pause()
    {

        mplayer.pause();
//      mplayer.release();
    }

    @Override
    public void seekTo(int pos) 
    {

        mplayer.seekTo(pos);
    }

    @Override
    public void start()
    {

        mplayer.start();

    }
}

1 个答案:

答案 0 :(得分:0)

简单使用服务,例如你可以做这样的事情

public class MediaPlayerSevice extends Service implements OnCompletionListener, 
                                                      OnPreparedListener, 
                                                      OnErrorListener {

private String playURI      = "";
private String songName     = "";
private String albumName    = "";       
private String songDuration = "";

public MediaPlayer mediaPlayer;

private boolean playingAudio = false;

private int seek_position = 0;
public final static String LOGTAG = "MediaPlayerSevice";

public class  MediaPlayerBinder extends Binder{

    public MediaPlayerSevice getService() {

        return MediaPlayerSevice.this;
    }
}

private final IBinder mBinder = new MediaPlayerBinder();

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {



     return START_STICKY;
}



public void startingAudioPlayback(String playURI,
                                  String songName,
                                  String albumName,
                                  String songDuration) throws IllegalArgumentException, 
                                                                          SecurityException, 
                                                                          IllegalStateException, 
                                                                          IOException {

    if (playingAudio) {
        return;
    }

    this.playURI      = playURI;
    this.songName     = songName;
    this.albumName    = albumName;      
    this.songDuration = songDuration;

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setOnCompletionListener(this);  
    mediaPlayer.setOnPreparedListener(this);
    mediaPlayer.setOnErrorListener(this);
    mediaPlayer.setDataSource(playURI);
    mediaPlayer.prepare();

    playingAudio = true;

}

public void changeAudioPlayback(String playURI,
                                String songName,
                                String albumName,
                                String songDuration) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException {

    if (playingAudio) {
        return;
    }

    this.playURI      = playURI;
    this.songName     = songName;
    this.albumName    = albumName;      
    this.songDuration = songDuration;

    if(mediaPlayer==null)
       mediaPlayer = new MediaPlayer();

    mediaPlayer.stop();
    mediaPlayer.reset();

    mediaPlayer.setDataSource(playURI);
    mediaPlayer.prepare();

    playingAudio = true;

}



public void stopPlay(){

      if(mediaPlayer!=null){
          mediaPlayer.stop();
          mediaPlayer.release();
          mediaPlayer = null;
       }

}


public int getCurrentPosition() {

    if(mediaPlayer!=null)
        return mediaPlayer.getCurrentPosition();
    else
        return 0;
}

public int getDuration() {
    if(mediaPlayer!=null)
        return mediaPlayer.getDuration();
    else
        return 0;
}

public void seekTo(int i) {
    if(mediaPlayer!=null)
       mediaPlayer.seekTo(i);

}

public boolean isPlaying() {

    if(mediaPlayer!=null)
       return mediaPlayer.isPlaying();
    else
       return false;
}

public void start() {

    if(mediaPlayer!=null)
       mediaPlayer.start();

}

public void pause() {

    if(mediaPlayer!=null)
       mediaPlayer.pause();

}

public int getVideoWidth() {

    if(mediaPlayer!=null)
       mediaPlayer.getVideoWidth();

    return 0;
}

public int getVideoHeight() {

    if(mediaPlayer!=null)
       mediaPlayer.getVideoHeight();

    return 0;
}




@Override
public void onPrepared(MediaPlayer mediaPlayer) {



      seekTo(seek_position);
      mediaPlayer.start();


}

@Override
public void onCompletion(MediaPlayer mediaPlayer) {

    mediaPlayer.stop();
    mediaPlayer.release();
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {


    return false;
}

}