希望MediaPlayer在屏幕锁定时继续运行

时间:2014-02-13 13:47:09

标签: android media-player android-mediaplayer

我怎么能做到这一点,即使手机被锁定并且屏幕关闭,我的MediaPlayer仍然继续播放,认为它可能需要做一些使其成为服务但不确定的事情。如果是这样,我怎么能将其更改为服务还是更容易修复?

任何帮助都会很棒!

这是代码:

 public class player2 extends Activity implements Runnable {


private  MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3;  //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();


   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.player_2);
        pauseicon = (ImageButton) findViewById(R.id.pauseicon);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        getActionBar().setDisplayHomeAsUpEnabled(true);



        mfile[0] = R.raw.sound04;  //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
        mfile[1] = R.raw.sound05;  //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
        mfile[2] = R.raw.sound06;
        // Listeners
        /**
         * Play button click event
         * plays a song and changes button to pause image
         * pauses a song and changes button to play image
         * */


        try{
             mp = MediaPlayer.create(player2.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
             mp.seekTo(0);
             mp.start(); ;         
             progressBar.setVisibility(ProgressBar.VISIBLE);
             progressBar.setProgress(0);
             progressBar.setMax(mp.getDuration());
             new Thread(this).start();

         } catch (IllegalArgumentException e) {
             e.printStackTrace();
         } catch (IllegalStateException e) {
             e.printStackTrace();
         }

        mp.setOnCompletionListener(new OnCompletionListener() {

            public void onCompletion(MediaPlayer mp) {
                pauseicon.setImageResource(R.drawable.playicon);
            }
        });

        pauseicon.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                 // No need to check if it is pauseicon

        if(mp.isPlaying()){
            mp.pause();
         ((ImageButton) v).setImageResource(R.drawable.playicon);

        } else {
            mp.start();
            ((ImageButton) v).setImageResource(R.drawable.pauseicon);
     }}});

   }
   static boolean runThread = true;
   public void run() {
        while ( runThread )  {
              int currentPosition=0;
              int total = mp.getDuration();
              if ( mp != null && currentPosition <= total )  {
              try {
                 Thread.sleep(1000);
                 currentPosition= mp.getCurrentPosition();
              } catch (InterruptedException e) {
                 return;
              } catch (Exception e) {
                 return;
              }            
              progressBar.setProgress(currentPosition);
           } else
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
        }
        runThread = false; 
    }
   @Override
   protected void onStop() {
       super.onStop();
       if (mp != null && mp.isPlaying()){
           mp.pause();

       }
   }

   @Override
   public void onResume()
   {
   super.onResume();

   if (mp != null){
         if(!mp.isPlaying())
            try {
                mp.prepare();
            } catch (IllegalStateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             mp.start();

     }
   } 


   @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);

            return true;
        default:
            return super.onOptionsItemSelected(item);

    }

       }

    }

1 个答案:

答案 0 :(得分:3)

按照下面的教程...在以下教程中,我将.mp3文件存储在原始文件夹中。如果您已将其存储在SD卡中并动态获取该文件,则将其路径放入捆绑包并通过意图发送,您可以使用onStartCommand()方法获取服务。

MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

  Button startPlaybackButton, stopPlaybackButton;
  Intent playbackServiceIntent;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startPlaybackButton = (Button) this.findViewById(R.id.StartPlaybackButton);
    stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);

    startPlaybackButton.setOnClickListener(this);
    stopPlaybackButton.setOnClickListener(this);

    playbackServiceIntent = new Intent(this, BackgroundAudioService.class);
  }

  public void onClick(View v) {
    if (v == startPlaybackButton) {
      startService(playbackServiceIntent);
      finish();
    } else if (v == stopPlaybackButton) {
      stopService(playbackServiceIntent);
      finish();
    }
  }
}

BackgroundAudioService.java

public class BackgroundAudioService extends Service implements OnCompletionListener {
      MediaPlayer mediaPlayer;

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

      @Override
      public void onCreate() {
          mediaPlayer = MediaPlayer.create(this, R.raw.abc);// YOUR FILE NAME
          mediaPlayer.setOnCompletionListener(this);
          Log.v("TEST", "1");
      }

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

         if (!mediaPlayer.isPlaying()) {
             Log.v("TEST", "2");
          mediaPlayer.start();
        }
        return START_STICKY;
      }

      public void onDestroy() {
        if (mediaPlayer.isPlaying()) {
          mediaPlayer.stop();
        }
        mediaPlayer.release();
      }

      public void onCompletion(MediaPlayer _mediaPlayer) {
        stopSelf();
      }

    }

activity_main.xml中

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Background Audio Player"
        />
   <Button android:text="Start Playback" android:id="@+id/StartPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
   <Button android:text="Stop Playback" android:id="@+id/StopPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>

不要忘记在下面的manifest.xml中声明服务,

<service android:name="com.demo.tute.BackgroundAudioService" />