Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause a music player programmatically

Tags:

android

I have used MUSIC_PLAYER in my application by starting like this:

Intent myint = new Intent("android.intent.action.MUSIC_PLAYER");
startActivity(myint);

And I want to pause this player. How do I do that?

import android.media.AudioManager;

import android.media.MediaPlayer;

import android.os.Bundle;

import android.app.Activity;

import android.content.Intent;

import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread mtr = new Thread(){
            public void run()
            {
                try {
                    Intent myint = new Intent("android.intent.action.MUSIC_PLAYER");
                    startActivity(myint);
                    sleep(50000);
                    // Here I want to pause my application after those 50 seconds.
                }
                catch(InterruptedException e){
                    e.printStackTrace();
                }
                finally{
                    Intent myint = new Intent("nextscreen");
                    startActivity(myint);
                }
            }
        };
        mtr.start();
    }
}
like image 429
Vamsi Pavan Mahesh Avatar asked Nov 22 '12 18:11

Vamsi Pavan Mahesh


1 Answers

In Samsung devices, you can control the music player with these intents:

ICS:
"com.android.music.musicservicecommand.play"
"com.android.music.musicservicecommand.pause"
"com.android.music.musicservicecommand.next"
...

JB:
"com.sec.android.app.music.musicservicecommand.play"
"com.sec.android.app.music.musicservicecommand.pause"
"com.sec.android.app.music.musicservicecommand.next"
...

context.sendBroadcast(new Intent("com.sec.android.app.music.musicservicecommand.pause"));

Another solution is requestAudioFocus in AudioManager (do not forget to release it with abandonAudioFocus). For example:

...
((AudioManager)getSystemService(Context.AUDIO_SERVICE)).requestAudioFocus(listener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
...

...
((AudioManager)getSystemService(Context.AUDIO_SERVICE)).abandonAudioFocus(listener);
...
like image 200
Ivan Avatar answered Sep 26 '22 23:09

Ivan