how to resume my audio in Android? - java

I have to implemented application for creating audio with the status of pause and resume and when my app as an when start the audio is start and when I press the back button on the emulator the audio music is on pause state but When my activity comes back to the foreground from the stopped state my audio music is not resumed. Here is my code.
public class Audio_Activity extends Activity
{
private MediaPlayer mp;
Button btnStartStop ;
Button btnChapter ;
Button btnOne;
Button btnTwo;
Button btnThree;
Button btnFour;
Button btnFive;
int length;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
if(mp!=null)
{
mp.setLooping(false);
mp.start();
btnChapter.setEnabled(false);
System.out.println("B4 button Click!!!!");
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
mp.stop();
mp.release();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
btnStartStop.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
if(mp.isPlaying())
{
if(mp!=null)
{
mp.pause();
}
}
else
{
// Resume song
if(mp!=null)
{
mp.start();
}
}
}
});
btnOne.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
imgVw.setImageResource(R.raw.chocklate);
}
}
);
btnTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.creame);
}
});
btnThree.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.schocklate);
}
});
btnFour.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.pinapple);
}
});
btnFive.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imgVw.setImageResource(R.raw.strobery);
}
});
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
}
#Override
protected void onStart()
{
super.onStart();
System.out.println("Activity is Started !!!");
}
#Override
protected void onRestart() {
super.onRestart();
System.out.println("Activity is Re-Started !!!");
if(mp.isPlaying())
{
if(mp!=null)
{
length=mp.getCurrentPosition();
mp.seekTo(length);
mp.start();
}
}
}
#Override
protected void onPause() {
super.onPause();
System.out.println("Activity is Pause!!!");
}
#Override
protected void onStop() {
super.onStop();
System.out.println("Activity is Stop !!!");
}
#Override
protected void onDestroy() {
super.onDestroy();
System.out.println("Activity is Destroyed !!!");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{ //Back key pressed
//Things to Do
if(mp!= null)
{
if(mp.isPlaying())
{
mp.pause();
//mp=null;
}
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}

You should use android MediaPlaybackService for background play,Pause, stop or just open the activity by clicking the Notification. when click on back button it will bind a PendingIntent to with the button click event or buttons on the notification bar for controlling audio playbacks.
Use this Gist Code for AudioPlayer, try o use MediaPlaybackService class or try to reverse engineer this owncloud code.

Your code is not correct. You should not bother backbutton etc, but activity life cycle. You should pause your audio in onPause() and resume in onResume(). So move code to onPause() and get rid of onKeyDown() and move code from your onRestart() to onResume(). And remove all methods you do not need, line onDestroy(), onStart() etc

Related

Use public boolean onKeyDown in all activities

I'm new in Android Studio and I have created a simple application with 10 activities.
Now, I want to intercept the KeyEvent.KEYCODE_BACK from the user in all of my activities.
I'm opening a dialog when KEYCODE_BACK. It's ok in my MainActivity but I don't want to copy this code in all of my activities.
Would anyone have an idea ?
public class MainActivity extends AppCompatActivity
{
Dialog myDialog;
Button BoutonAccepter;
Button BoutonRefuser;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
myDialog = new Dialog(this);
if (keyCode == KeyEvent.KEYCODE_BACK)
{
myDialog.setContentView(R.layout.popup);
BoutonAccepter = (Button) myDialog.findViewById(R.id.BoutonAccepter);
BoutonRefuser = (Button) myDialog.findViewById(R.id.BoutonRefuser);
BoutonAccepter.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Non", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
BoutonRefuser.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Oui", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
myDialog.show();
}
else
{
return super.onKeyDown(keyCode, event);
}
return true;
}
}
I think that you should separate this code into a separate abstract class and make exdends of this class for all your activities
public abstract class BaseActivity extends AppCompatActivity
{
Dialog myDialog;
Button BoutonAccepter;
Button BoutonRefuser;
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
myDialog = new Dialog(this);
if (keyCode == KeyEvent.KEYCODE_BACK)
{
myDialog.setContentView(R.layout.popup);
BoutonAccepter = (Button) myDialog.findViewById(R.id.BoutonAccepter);
BoutonRefuser = (Button) myDialog.findViewById(R.id.BoutonRefuser);
BoutonAccepter.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Non", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
BoutonRefuser.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getApplicationContext(), "Oui", Toast.LENGTH_LONG).show();
myDialog.dismiss();
}
});
myDialog.show();
}
else
{
return super.onKeyDown(keyCode, event);
}
return true;
}
}
And in all activities
public class ActivityA extends BaseActivity {
}

how to stop a Runnable running on an UIThread

I have a Runnable on a UIThread updating a SeekBar while a MediaPlayer is playing. Yet, when I switch to another activity my application crashes with an exception cause the Runnable keeps on forever even after the MediaPlayer has been destroyed.
This is my code:
public class Guide extends AppCompatActivity implements MediaPlayer.OnPreparedListener {
Button back;
private MediaPlayer m_audio_player;
private Handler m_handler_seek_bar = new Handler();
private SeekBar m_seek_bar;
private Runnable m_seek_bar_runnable;
private void set_up_audio(){
m_audio_player = MediaPlayer.create(this, g_audio[NativeLib.get_active_landmark()] );
m_audio_player.setOnPreparedListener(this);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guide);
implement_back_button();
set_up_audio();
}
#Override
protected void onStart() {
super.onStart();
set_up_seek_bar();
}
private void set_up_seek_bar() {
m_seek_bar = (SeekBar) findViewById(R.id.seek_bar);
m_seek_bar.setMax(m_audio_player.getDuration());
m_seek_bar_runnable = new Runnable() {
#Override
public void run() {
if(m_audio_player != null ){
m_seek_bar.setProgress(m_audio_player.getCurrentPosition());
}
m_handler_seek_bar.postDelayed(this, 1000);
}
};
// update Seekbar on UI thread
Guide.this.runOnUiThread(m_seek_bar_runnable);
m_seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
#Override
public void onStartTrackingTouch(SeekBar seekBar) {}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(m_audio_player != null && fromUser){
m_audio_player.seekTo(progress);
}
}
});
}
#Override
protected void onStop() {
if (debug_mode) Log.d(TAG, "onStop");
if (m_audio_player.isPlaying()) {
m_audio_player.stop();
}
m_audio_player.release();
super.onStop();
findViewById(R.id.activity_guide).removeCallbacks(m_seek_bar_runnable);
}
// return button
private void implement_back_button() {
final Intent intent = new Intent(/* pointing at some other activity */);
back = (Button) findViewById(R.id.back_button);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
}
}
You need to use:
m_handler_seek_bar.removeCallbacks(m_seek_bar_runnable);
to remove the runnable from handler
#Override
protected void onStop() {
if (debug_mode) Log.d(TAG, "onStop");
if (m_audio_player.isPlaying()) {
m_audio_player.stop();
}
m_audio_player.release();
m_handler_seek_bar.removeCallbacks(m_seek_bar_runnable);
super.onStop();
}
Alternatively you can override the onPause() method of the activity:
#Override
protected void onPause() {
m_handler_seek_bar.removeCallbacks(m_seek_bar_runnable);
super.onPause();
}
Remove all the callbacks from the Handler in onStop using handler.removeCallbacks

How to always check a condition in Android?

I want to develop an app to toggle the device's audio status. If the audio status is silent then my button's text should be "silent", if it's normal the text should be "normal"
Here is my only class:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button btn1= (Button) findViewById(R.id.btn1);
final AudioManager audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
btn1.setText("Normal");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
btn1.setText("Silent");
}
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
}
});
How can I always check this condition in Android ?
If you need to get the mode of current ringer even if it was changed outside from you application context then you should register a BroadcastReceiver for AudioManager.RINGER_MODE_CHANGED_ACTION.
This receiver will be called everytime someone changes the ringer mode.
Do this inside onCreate.
BroadcastReceiver receiver=new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
btn1.setText("Normal");
}
}
};
IntentFilter filter=new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(receiver,filter);
Just do this
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
what your are doing is
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (audio.getRingerMode()==AudioManager.RINGER_MODE_NORMAL)
{
audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
btn1.setText("Silent");
}
else if (audio.getRingerMode()==AudioManager.RINGER_MODE_SILENT)
{
audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
btn1.setText("Normal");
}
}
});
}
});

onPause in eclipse gives syntax error and void is invalid type

I'm using the onPause method in my activity, but I'm receiving the following errors:
Syntax error, insert ";"to complete LocalVariableDeclarationStatement
void is an invalid type for the variable onPause
Code:
public class MusicActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
final MediaPlayer MP = MediaPlayer.create(MusicActivity.this, R.raw.burntumber);
Button burntumberPlay = (Button) findViewById(R.id.start1Button);
burntumberPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MP.start();
}
});
Button burntumberStop = (Button) findViewById(R.id.stop1Button);
burntumberStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MP.pause();
MP.seekTo(0);
}
});
#Override
protected void onPause{
super.onPause();
MP.stop();
MP.release();
};
}
}
EDIT:
public class MusicActivity extends Activity {
MediaPlayer MP = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
MP = MediaPlayer.create(MusicActivity.this, R.raw.burntumber);
Button burntumberPlay = (Button) findViewById(R.id.start1Button);
burntumberPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MP.start();
}
});
Button burntumberStop = (Button) findViewById(R.id.stop1Button);
burntumberStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//MP.stop(); //won't restart when start() is run again
MP.pause();
//MP.seekTo(0);
}
});
}
#Override
protected void onPause{
super.onPause();
MP.stop();
MP.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.music, menu);
return true;
}
}
Errors:
Syntax error, insert ";" to complete FieldDeclaration
The annotation #Override is disallowed for this location
void is an invalid type for the variable onPause
Your method is inside onCreate() and has a ";" at the end of it. It is a separate method so should not be inside a method.
public class MusicActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
// onCreate() code
}
#Override
protected void onPause{
super.onPause();
MP.stop();
MP.release();
}
Edit
You are also missing the "()" for the onPause() method. That is why Eclipse thinks it is a Field instead of a method. Change it to
#Override
protected void onPause(){ // missing the parenthesis here
super.onPause();
MP.stop();
MP.release();
}
Remove SemiColon at the end of onPause Method
protected void onPause{
super.onPause();
MP.stop();
MP.release();
}

How to play, stop and pause working on media player instance in android ?

I want to develop media player type of application which has two button one for play and pause and one for stop. I take two image buttons in my layout file and reference it in Java file and code like this which I put here, but when I click on stop button audio is getting stopped but then I want replay audio file; but I cant play with play button.
my Java code below
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_aarti_fragment, container, false);
btnplay=(ImageButton)v.findViewById(R.id.btnplay);
btnstop=(ImageButton)v.findViewById(R.id.btnstop);
seekbar=(SeekBar)v.findViewById(R.id.seekbar);
mp = MediaPlayer.create(getActivity(), R.raw.arti);
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
btnplay.setImageResource(R.drawable.ic_action_play);
Toast.makeText(getActivity(), "Pause",Toast.LENGTH_SHORT).show();
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
}
}
});
return v;
}
Use This:
private BackgroundSound mBackgroundSound;
private MediaPlayer player;
public class BackgroundSound extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
player = MediaPlayer.create(HomePage.this, R.raw.background);
AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
float actualVolume = (float) audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
player.setLooping(true); // Set looping
player.setVolume(volume, volume);
player.start();
return null;
}
}
For Playing:
mBackgroundSound = new BackgroundSound();
mBackgroundSound.execute();
For Stop:
mBackgroundSound.cancel(true);
if (player != null) {
player.stop();
player.release();
}
For Pause:
if (player != null) {
player.pause();
}
Try this it will help you....
//Click Listener on Image Button with play and Pause method
PLAY.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Play-Pause();
}
});
//Play Pause method...........
public void Play-Pause(){
if (mediaPlayer.isPlaying()) {
PLAY.setImageResource(R.drawable.pause);
mediaPlayer.pause();
} else {
PLAY.setImageResource(R.drawable.play);
mediaPlayer.start();
}
}
Once a media player is stopped, you need to call prepare on it again to get it to a state where you can call start(). Look at the state diagram here http://developer.android.com/reference/android/media/MediaPlayer.html#pause%28%29
Check this code, its better and simple solution !
public class MainActivity extends AppCompatActivity {
MediaPlayer mp;
Switch sw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = MediaPlayer.create(this,R.raw.nokia);
sw = findViewById(R.id.sw);
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mp.setLooping(true);
}
});
}
public void play(View v){
mp.start();
}
public void pause(View v){
if(mp.isPlaying())
mp.pause();
}
public void stop(View v){
if(mp.isPlaying()) {
boolean loop=mp.isLooping();
mp.stop();
mp = MediaPlayer.create(this, R.raw.nokia);
mp.setLooping(loop);
}
}
}

Categories

Resources