Seekbar not setting up with Mediaplayer android - java

I have been working in an app where i have to play a media with seekbar. The layout consumes recyclerview. The code i used is
private class ViewHolder2 extends RecyclerView.ViewHolder {
public TextView name, filename;
ImageView img, play;
SeekBar seekBar;
public ViewHolder2(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
filename = (TextView) view.findViewById(R.id.filename);
img = (ImageView) view.findViewById(R.id.image);
play = (ImageView) view.findViewById(R.id.play);
seekBar = (SeekBar) view.findViewById(R.id.seekbar);
}
}
And after initialising the class like above in my adapter class, in my play button onclick i coded like below.
vh2.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isFilePresent("Bombay.mp3")) {
final MediaPlayer mediaPlayer1 = new MediaPlayer();
try {
if (mediaPlayer1 != null) {
mediaPlayer1.setDataSource(audioPath);
mediaPlayer1.prepare();
mediaPlayer1.start();
}
int mediaPlayerDuration = mediaPlayer1.getDuration();
vh2.seekBar.setMax(mediaPlayerDuration);
vh2.seekBar.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 (mediaPlayer1 != null && fromUser) {
mediaPlayer1.seekTo(progress * 1000);
}
}
});
handler = new Handler();
//Make sure you update Seekbar on UI thread
((Activity) context).runOnUiThread(new Runnable() {
#Override
public void run() {
if (mediaPlayer1 != null) {
int mCurrentPosition = mediaPlayer1.getCurrentPosition() / 1000;
vh2.seekBar.setProgress(mCurrentPosition);
}
handler.postDelayed(this, 1000);
}
});
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "Oops! File not found!", Toast.LENGTH_SHORT).show();
}
}
});
where vh2 is nothing but the ViewHolder2 class instance. I got my song playing on button click, but seek bar not working.
My seekbar initialisation in xml file
<SeekBar
android:id="#+id/seekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Can you guys please help on what i am missing in this code?

Related

MemoryLeakMonitor.jar is not exist! Some songs are playing and some songs are causing app crash

I can see all the songs in my app and all the songs are playing but I have some songs
So that when clicked
This application crashes
90 percent of my songs are playing but 10 percent of the songs are not playing. Clicking on these songs will cause the app to crash.
I can see that everything is fine . Can anyone tell me what the problem is?
logcat error....
2022-03-08 21:01:09.236 14607-14635/com.codewithmorshed.recyclerviewmusikplayer E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile#60951ba
2022-03-08 21:01:09.241 14607-14626/com.codewithmorshed.recyclerviewmusikplayer E/MemoryLeakMonitorManager: MemoryLeakMonitor.jar is not exist!
this is MainActivity...........
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
listView = findViewById(R.id.listView);
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
Toast.makeText(MainActivity2.this, "Thanks for Allow", Toast.LENGTH_SHORT).show();
ArrayList<File> mysongs = fatchsongs(Environment.getExternalStorageDirectory());
String[] items = new String[mysongs.size()];
for (int i=0;i<mysongs.size(); i++){
items [i] = mysongs.get(i).getName().replace(".mp3","");
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity2.this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
// intenti onno activity ta jawar jonno and oikane textview gan show koranor jonno bebohito hoyyceee;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity2.this, MainActivity3.class);
String currentSong = listView.getItemAtPosition(position).toString();
intent.putExtra("Songlist", mysongs);
intent.putExtra("currentSong", currentSong);
intent.putExtra("position", position);
startActivity(intent);
}
});
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
})
.check();
}
ArrayList<File> fatchsongs (File file){
ArrayList arrayList = new ArrayList();
File[] songs = file.listFiles();
if (songs != null) {
for (File myfile : songs) {
if (myfile.isDirectory() && !myfile.isHidden()) {
arrayList.addAll(fatchsongs(myfile));
} else {
if (myfile.getName().endsWith(".mp3") && !myfile.getName().startsWith(".")) {
arrayList.add(myfile);
}
}
}
}
return arrayList;
}
}
this is PlayerActiviy.....
public class PlayerActiviy extends AppCompatActivity {
TextView textView;
SeekBar seekBar;
ImageView play, next, previous;
MediaPlayer mediaPlayer;
//textview ta gan er name show korate bebhoti ekti holo
// Ager activity ir File jeikane theke gan show hove
//String eita textView ta show koranor jonno bebohito hoyce
ArrayList<File> arrfile;
String textContent;
int position;
Thread updateseek;
private CircleLineVisualizer circleLine;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
textView = findViewById(R.id.textView);
seekBar = findViewById(R.id.seekBar);
play = findViewById(R.id.play);
next = findViewById(R.id.next);
previous = findViewById(R.id.previous);
circleLine = findViewById(R.id.circleLine);
// Text view ta gan er name show koranor jonno bebohito
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
arrfile = (ArrayList) bundle.getParcelableArrayList("Songlist");
textContent = intent.getStringExtra("currentSong");
textView.setText(textContent);
position = intent.getIntExtra("position", 0);
Uri uri = Uri.parse(arrfile.get(position).toString());
mediaPlayer = MediaPlayer.create(this, uri);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setProgress(mediaPlayer.getCurrentPosition());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
updateseek = new Thread(){
#Override
public void run() {
int currentposition = 0;
try {
while(currentposition<mediaPlayer.getDuration()){
currentposition = mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentposition);
sleep(800);
}
}
catch (Exception e){
e.printStackTrace();
}
}
};
updateseek.start();
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()){
play.setImageResource(R.drawable.play);
mediaPlayer.pause();
}
else{
play.setImageResource(R.drawable.pause);
mediaPlayer.start();
}
}
});
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (position !=0){
position = position -1;
}
else {
position = arrfile.size() -1;
}
Uri uri = Uri.parse(arrfile.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setProgress(mediaPlayer.getCurrentPosition());
play.setImageResource(R.drawable.pause);
textContent = arrfile.get(position).getName().toUpperCase(Locale.ROOT);
textView.setText(textContent);
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.release();
if (position !=arrfile.size() -1){
position = position +1;
}
else {
position =0;
}
Uri uri = Uri.parse(arrfile.get(position).toString());
mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
play.setImageResource(R.drawable.pause);
seekBar.setProgress(mediaPlayer.getCurrentPosition());
textContent = arrfile.get(position).getName().toString();
textView.setText(textContent);
}
});
}
}

Basic music player - next and previous button

this is my last post about any kind of music player ever but I really need help. Im working on basic android music player application and Im having trouble to create NEXt and PREVIOUS buttons. So i pretty pretty please if anyone can get me out of that.I have tried something more about that downhere THANK YOU. I have created this yet:
Main Application Java file
public class MainActivity extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile= null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ImageButton playButton = null;
private ImageButton previousButton = null;
private ImageButton nextButton = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingseekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
1);
selectedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
playButton = (ImageButton) findViewById(R.id.play);
previousButton = (ImageButton) findViewById(R.id.previous);
nextButton = (ImageButton) findViewById(R.id.next);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
previousButton.setOnClickListener(onButtonClick);
}
}
#Override
protected void onListItemClick(ListView list, View view, int position,long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
#Override
protected void onDestroy(){
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
selectedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e){
e.printStackTrace();
} catch (IllegalStateException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
// seekbar.setSecondaryProgressTintMode(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter{
MediaCursorAdapter(Context context, int layout, Cursor c){
super(context, layout,c,
new String[] {MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[] {R.id.displayname, R.id.title,R.id.duration});
}
#Override
public void bindView(View view,Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.listitem, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto < player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.previous: {
int seekto = player.getCurrentPosition() - STEP_VALUE;
if (seekto < player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingseekBar = false;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fomUser) {
if (isMovingseekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChange");
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingseekBar = true;
}
};
}
I have already did switch with NEXT and PREVIOUS buttons and I have tried to make them work BUT I ended up with getting at the and or beggining of the song not the NEXT or PREVIOUS.

Need a sound to play every second if a button is toggled

I have a toggle button and i need the 'mp' sound to play every second if that button is toggled.The code below is what i tried and it does play the sound every second but the button stops responding so i can't turn it off.
ToggleButton btn = findViewById(R.id.button);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.beat);
btn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
while (isChecked) {
mp.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thank you in advance.
Never use Thread.sleep(1000) it is the terrible thing you can do to the app. Your app is not
responsding because you are putting Main thread of app to sleep.
I have created this class for you for desmonstration. you can tweak is further to your needs.
private Handler soundHandler = new Handler();
private int delay = 1000;
private Runnable soundRunnable;
private MediaPlayer mediaPlayer;
private boolean isToggleChecked;
#Override protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton toggleButton = findViewById(R.id.button);
mediaPlayer = MediaPlayer.create(this, R.raw.beat);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked){
isToggleChecked = isChecked;
if(isChecked){
playSound();
}else {
stopSound();
}
}
});
}
#Override protected void onResume(){
super.onResume();
if(isToggleChecked){
playSound();
}
}
// this will make sure sound stops when app stops or goes in background
#Override
protected void onPause() {
soundHandler.removeCallbacks(soundRunnable);
super.onPause();
}
private void playSound(){
soundHandler.postDelayed(new Runnable() {
public void run() {
soundRunnable = this;
if(mediaPlayer != null) {
mediaPlayer.start();
}
soundHandler.postDelayed(soundRunnable, delay);
}
}, delay);
}
private void stopSound(){
if(mediaPlayer != null){
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
soundHandler.removeCallbacks(soundRunnable);
}
}
}
I found an answer to another question and modified it to fit my needs and now it works perfectly.Here is the solution/code.
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer = null;
int delayMillis;
Handler handler;
Runnable runnable;
private boolean isToggleChecked;
private ToggleButton toggleButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggleButton = findViewById(R.id.button);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
};
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
isToggleChecked = true;
toggleMediaPlayer();
}
else {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
handler.removeCallbacks(runnable);
isToggleChecked = false;
}
}
});
}
#Override
public void onResume() {
super.onResume();
if (isToggleChecked) {
toggleButton.setChecked(true);
}
else {
toggleButton.setChecked(false);
}
}
private void toggleMediaPlayer(){
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
handler.removeCallbacks(runnable);
}else{
mediaPlayer = MediaPlayer.create(this, R.raw.beat);
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
delayMillis = 1000;
handler.postDelayed(runnable,delayMillis);
}
});
}
}
}

Slide Show using ViewPager and Timer in Android

I have created a very simple slide show using viewpager. To auto slide I have used a timer for every 5 seconds. I have a X button to close the slide show in the middle of the slide. When I press the X the app closes the slideshow goes to MainActivity. All this is working fine but when I open the slideshow activity
again from MainActivity the first image comes up properly but then the next one jumps to last image from the array, doesn't show other images. Could be timer issue or something else. I am purging and cancelling the timer
Please check my code below:
I have set the images in Array and adding them to arrayList.
private static final Integer[] LANDSCAPEIMAGES = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5,
R.drawable.image6, R.drawable.image7, R.drawable.image8, R.drawable.image9, R.drawable.image10,
R.drawable.image11};
private ArrayList<Integer> imagesArray = new ArrayList<Integer>();
private Timer swipeTimer;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.slideshow);
swipeTimer = new Timer();
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//init();
}
else if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//init();
}
else
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
initLand();
}
mPager.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
}
private void initLand()
{
for (int i = 0; i < LANDSCAPEIMAGES.length; i++)
imagesArray.add(LANDSCAPEIMAGES[i]);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(new SlidingImage_Adapter(StartSlideShow.this, imagesArray, this));
NUM_PAGES = LANDSCAPEIMAGES.length;
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable()
{
public void run()
{
//Comment for no loop.
/*if (currentPage == NUM_PAGES) {
currentPage = 0;
}*/
mPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer.schedule(new TimerTask() {
#Override
public void run()
{
handler.post(Update);
}
}, 5000, 5000);
}
//TO FINISH THE ACTIVITY AND STOP TIMER()
#Override
public void pagerItemSelected()
{
Log.e("Value", "=It is coming here");
finish();
onBackPressed();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Log.e("Value", "=onBackPressed");
swipeTimer.purge();
swipeTimer.cancel();
}
My PagerAdapter:
public class SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
OnPagerItemSelected mListener;
public SlidingImage_Adapter(Context context,ArrayList<Integer> IMAGES, OnPagerItemSelected listener) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
mListener = listener;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position)
{
View imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false);
ImageView quit = (ImageView) imageLayout.findViewById(R.id.closeimage);
quit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent readMore = new Intent(v.getContext(), MainActivity.class);
v.getContext().startActivity(readMore);
// ((Activity) context).finish();
mListener.pagerItemSelected();
}
});
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
Log.e("Value"," - " + position);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
public interface OnPagerItemSelected {
void pagerItemSelected();
}
}

How to play audio continuously while orientation going to change in android

I have develop application like media player to use for playing audio file from source but issue when I am change the orientation portrait to landscape button and other widget not working and other that is when I am again change orientation landscape to portrait so same issue button and seek bar is not working
my code is here
public class Aarati_Activity extends Fragment
{
private ImageButton btnplay;
private SeekBar seekbar;
MediaPlayer mp;
private ImageButton btnstop;
private int finalTime = 0;
private int startTime = 0;
private int oneTimeOnly = 0;
Handler handler=new Handler();
public Aarati_Activity() {}
int audiocurrent;
int audiomax;
private int mp_progress;
#Override
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);
seekbar.setClickable(true);
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekchange();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
mp = MediaPlayer.create(getActivity(), R.raw.arti);
audiomax=mp.getDuration();
audiocurrent=mp.getCurrentPosition();
btnstop.setOnClickListener(new OnClickListener() {
#Override
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;
}
#SuppressLint("NewApi")
public void seekchange()
{
mp_progress=seekbar.getProgress();
mp.seekTo(mp_progress);
}
private Runnable UpdateSongTime = new Runnable()
{
public void run()
{
startTime = mp.getCurrentPosition();
seekbar.setProgress((int)startTime);
handler.postDelayed(this, 100);
}
};
}
You need to use Service to play song. It will allow you to play song even when app is in background
Tutorial
Basically, from the MVC (Model-View-Controller) viewpoint, an Activity is a Controller, the view hierarchy is the View, and the View and Controller get re-created each time the orientation changes. Meanwhile, song playing belongs to the Model.
Note that an activity has the methods onSaveInstanceState(Bundle) and onCreate(Bundle), and if the bundle passed to onCreate() is not null, it contains the information previously stored by onSaveInstanceState().
And there's also onRetainNonConfigurationInstance(). When the screen turns, the old activity is destroyed and a new activity is created, and these methods let the old activity pass important data to the new one.
Even after you create a service, you have to keep this MVC stuff in mind.

Categories

Resources