Reputation:
I have develop application which has many fragment activity like home, gallery, songs, other so my issue is when i play audio in songs fragment and then I press back button to get exit from the application but audio playing continuously so I want to code on back press button but I don't know how to work and which method should override like in activity finish() method in on back pressed method
my code
*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);
public void onClick(View v) {
if(mp.isPlaying())
{
mp.stop();
Toast.makeText(getActivity(), "Stop",Toast.LENGTH_LONG).show();
btnplay.setImageResource(R.drawable.ic_action_play);
try
{
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getActivity(),"Aarti Currently not playing",Toast.LENGTH_SHORT).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();
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if(oneTimeOnly == 0)
{
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
seekbar.setProgress((int)startTime);
handler.postDelayed(UpdateSongTime,100);
}
else
{ btnplay.setImageResource(R.drawable.ic_action_pause);
mp.start();
Toast.makeText(getActivity(), "Play",Toast.LENGTH_SHORT).show();
finalTime = mp.getDuration();
startTime = mp.getCurrentPosition();
if(oneTimeOnly == 0)
{
seekbar.setMax((int) finalTime);
oneTimeOnly = 1;
}
seekbar.setProgress((int)startTime);
handler.postDelayed(UpdateSongTime,100);
}
}
});
return v;*
}
Upvotes: 0
Views: 3306
Reputation: 8826
Instead of overriding back button etc, you should use fragment lifecycle methods.
You can override onStop() method in fragment to release media resource or stop.
@Override
public void onStop() {
super.onStop();
mp.release(); // or pause or stop.
Log.i(TAG, "onStop");
}
To control back button, in your activity class
@Override
public void onBackPressed() {
// do something, show toast message to confirm or go to another activity
}
Upvotes: 1