how to stop viewpager auto slide in android - android

I have made an android app in that i have implemented play pause function,But I only knows about play ,I don't know how to stop sliding on the same button click,I have used two functions for it as below,play is working but pause is not.!
onClick
if (!flag) {
play();
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setBackgroundResource(R.drawable.pause);
flag = true;
} else {
pause();
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setBackgroundResource(R.drawable.play_btn);
flag = false;
}
play and pause
void play() {
pos = viewPager.getCurrentItem();
ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
try {
if (pos <= adapter.getCount() - 1) {
viewPager.setCurrentItem(pos, true);
viewPager.setScrollDurationFactor(6);
handler.postDelayed(this, 3000);
pos++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
void pause() {
pos = viewPager.getCurrentItem();
ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
try {
if (pos <= adapter.getCount() - 1) {
viewPager.setCurrentItem(pos, true);
viewPager.setScrollDurationFactor(6);
handler.postDelayed(this, 300000);
pos++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}

in pause button click :
handler.removeCallbacksAndMessages(ViewPagerVisibleScroll);
Try this

Related

how to stop this running thread?

public class MainActivity extends Activity implements Runnable{
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
ProgressBar linProgressBar;
private long fileSize = 0;
Thread t1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.button1);
Button b2 = (Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
linProgressBar.setProgress(0);
t1.interrupt();
}
});
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
basicInitializations();
}
});
}
public void basicInitializations(){
linProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
linProgressBar.setProgress(0);
linProgressBar.setMax(100);
try{
t1 = new Thread()
{
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
linProgressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
t1.start();
}catch (Exception e) {
}
}
public int doSomeTasks() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}else if (fileSize == 400000) {
return 40;
}else if (fileSize == 500000) {
return 50;
}
}
return 100;
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
this is my main code and i could not stop this thread .
i want to stop it when i click the button b2(say cancel button).
the above code is not the original code and is a model , so please tell me how to stop that thread .
thankyou in advance . . . .
I have a alternate answer can try the same, inside your runnable loop always check a flag as run_flag, create it as a member variable and set it as true once you stared the loop, you can make it run_flag as false wenever you are done and at the same time you can set null to your thread also ... a safer way to come out through runnable loop and thread.
try{
t1 = new Thread()
{
public void run() {
while (progressBarStatus < 100 && run_flag == true) { // added run_flag here
// process some tasks
progressBarStatus = doSomeTasks();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
linProgressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
t1.start();
}catch (Exception e) {
}
Your thread spends most of its time in Thread.sleep(), which is helpful. The thread pointer, t1, is a class member, which is also helpful. From your button handler, you can check to see if t1 is still alive and, if so, call t1.interrupt();. This will cause the thread's current sleep and future sleeps to throw the InterruptedException... now you just need to modify your exception handler to quit the thread in that case.

Why the text in the handler are not updated?

I am trying to update two TextViews txtName and textEndName. When i debug sometimes it updates the text but rest of the time it does not works. Sometime it works but not not exactly what it is suppose to.What is the problem in the below given code ?
txtName = (TextView) findViewById(R.id.txtstarttag);
textEndName = (TextView) findViewById(R.id.txtendtag);
startSec = (TextView) findViewById(R.id.txtstartsecnd);
endSec = (TextView) findViewById(R.id.txtendsecnd);
btnplay = (ImageButton) findViewById(R.id.btnplay);
btnback = (Button) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((MyMixes) getParent()).goBack();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnClick();
}
});
splitArray();
Thread t = new Thread()
{
public void run()
{
while (isDownloading)
{
if (Data.filenames != null && Data.filenames.size() >= (getIntent() .getExtras().getInt("index") + 1) && Data.filenames.get(getIntent().getExtras() .getInt("index")) != null)
{
try
{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(Data.filenames.get(getIntent().getExtras().getInt("index")));
mediaPlayer.prepare();
mediaPlayer.start();
Timer t = new Timer();
handler.postDelayed(onEverySecond, 1000);
mediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.seekTo(0);
}
});
boolean isPlaying = mediaPlayer.isPlaying();
if(!isPlaying){
mediaPlayer.pause();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
isDownloading = false;
}
}
}
}
};
t.start();
}
private Runnable onEverySecond=new Runnable()
{
public void run()
{
if (mediaPlayer.isPlaying())
{
for (int i = index; i < intervals.length; i++)
{
if (i != index && mediaPlayer.getCurrentPosition() > intervals[i])
{
index = i;
handler.dispatchMessage(handler.obtainMessage());
handler.postDelayed(onEverySecond, 1000);
break;
}
}
}
}
};
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg) {
txtName.setText(arrName.get(index));
textEndName.setText(arrName.get(index+1));
super.handleMessage(msg);
}
};
public void splitArray()
{
strSplit = kggg.split("\n");// string array
intervals = new long[strSplit.length];
Time timer;
for (int j = 0; j < strSplit.length; j++)
{
split = strSplit[j];// string
split1 = split.split("-");// string array
arrName.add(split1[0]);
String timeq = split1[1];
String[] timed = timeq.split(":");
if(timed.length == 3)
{
timer = new Time(Integer.parseInt(timed[0].trim()), Integer.parseInt(timed[1].trim()), Integer.parseInt(timed[2].trim()));
intervals[j] = timer.getTime();
}
else if(timed.length == 2)
{
timer = new Time(0, Integer.parseInt(timed[0].trim()), Integer.parseInt(timed[1].trim()));
intervals[j] = timer.getTime();
}
else if(timed.length == 1)
{
timer = new Time(0, 0, Integer.parseInt(timed[0].trim()));
intervals[j] = timer.getTime();
}
}
for (int j = intervals.length-1; j >= 0 ; j--)
{
intervals[j] = intervals[j] - intervals[0];
}
}
public void btnClick()
{
k++;
k = k % 2;
startSong(k);
}
private void startSong(int i) {
if (i == 1) {
System.out.println("11111" + i);
btnplay.setImageResource(R.drawable.pause);
try {
System.out.println("start try chech------");
mediaPlayer.start();
} catch (Exception e) {
mediaPlayer.pause();
}
}
if (i == 0) {
btnplay.setImageResource(R.drawable.play);
mediaPlayer.pause();
System.out.println("00000" + i);
}
}
You shouldn't be doing this:
handler.dispatchMessage(handler.obtainMessage());
Try this instead:
handler.sendMessage(handler.obtainMessage());
EDIT: Added other things I noticed
I also see that in your Thread you have a loop while (isDownloading) and you set isDownloading to false in the finally block. This loop while never run more than once.
Also, you do
btnplay.setImageResource(R.drawable.play);
inside a thead. This isn't good. You need to do everything related to UI on the main (UI) thread.

android: Consultation about blinking screen

i try to make my screen blinking like this:
for (int i=0;i<10;i++)
{
targetView.setBackgroundColor(Color.BLUE);
for (int j=0;j<500;j++); //delay
targetView.setBackgroundColor(Color.RED);
}
but it wont work
Try this,
targetView.setBackgroundColor(Color.BLUE);
try {
Thread.sleep(5000); // milliseconds to wait...
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
targetView.setBackgroundColor(Color.RED);
EDIT
public class TSActivity extends Activity {
LinearLayout lin;
private int finalStatus = 0;
private Handler colorHandler = new Handler();
boolean flag = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lin = (LinearLayout)findViewById(R.id.linMain);
new Thread(new Runnable() {
public void run() {
while (finalStatus < 100) {
// process some tasks
finalStatus = doSomeTasks();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the color
colorHandler.post(new Runnable() {
public void run() {
if(flag)
{
lin.setBackgroundColor(Color.BLUE);
flag = false;
}
else
{
lin.setBackgroundColor(Color.GREEN);
flag = true;
}
}
});
}
}
}).start();
}
// color changer simulator... a really simple
public int doSomeTasks() {
long fileSize = 0;
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}
// ...add your own
}
return 100;
}
}
Hope this will help you..
Thanks...
You can use handler also.
Runnable r=new Runnable(){
public void run(){
if(red){
targetView.setBackgroundColor(Color.RED);
red=false;
}
else{
targetView.setBackgroundColor(Color.BLUE);
red=true;
}
if(!stop_blinking) handler.postDelayed(this,1000);
}
};
handler=new Handler();
handler.postDelayed(r,1000); //1000 is in mili secs.
stop_blinking is boolean which you need to set whenever you want the view to stop blinking.

Method inside Thread is going out of focus

I have a method which I am calling from onCreate( main thread). Inside the method I am calling one more method and a Runnable that calls the same method repeatedly. This is how it looks,
public void start() {
try {
if (start == 0) {
playpause.setBackgroundDrawable(getResources().getDrawable(
R.drawable.play));
initialPoiPlayStatus = true;
playAudio();
}
if (play) {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
// for displaying view stub
poi = listOfPOI.get(j);
int pos = mMediaPlayer.getCurrentPosition();
int convSeconds = -1;
convSeconds = ((int) (pos) / 1000);
// displaying the you tube pop up based on the parsed value
// from the plist
youTube(convSeconds);
// call the method to change the image while the audio is
// playing
changeImage();
seek_bar.setProgress(current_position);
notification = new Runnable() {
public void run() {
start();
}
};
handler.postDelayed(notification, 1000);
} else {
if (j != (listOfPOI.size() - 1)) {
firstPlay = true;
initialPoiPlayStatus = true;
j++;
playAudio();
start();
// retrieve mascot info
if (isNetworkAvailable() == true) {
receiveResponse();
} else {
}
} else {
threadHandler.sendEmptyMessage(0);
}
}
}
} catch (Exception e) {
System.out.println(poi.getPlistPath());
e.printStackTrace();
}
}
Now inside youtube,
private void youTube(int convSeconds) {
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
youtubeWebView = (WebView) findViewById(R.id.youtubewebView);
try {
if (poi.getIsYoutubePresent().equals("true")) {
//mMediaPlayer.pause();
isNetworkAvailable();
if (isNetworkAvailable() == true) {
String startTimeyoutube = poi.getYoutubestartTime();
Integer youTubeStartTime = Integer
.parseInt(startTimeyoutube);
if (convSeconds == youTubeStartTime) {
if (frameLayout.getVisibility() == View.GONE) {
frameLayout.setVisibility(View.VISIBLE);
slideUp = AnimationUtils.loadAnimation(this,
R.anim.slide_up);
frameLayout.startAnimation(slideUp);
}
final String youTubeurl = poi.getLink();
WebSettings websets = youtubeWebView.getSettings();
websets.setJavaScriptEnabled(true);
registerForContextMenu(youtubeWebView);
youtubeWebView
.setWebViewClient(new ItemsWebViewClient());
youtubeWebView.loadUrl(youTubeurl);
youtubeWebView.getSettings().setLayoutAlgorithm(
LayoutAlgorithm.SINGLE_COLUMN);
firstPlay = false;
initialPoiPlayStatus = false;
paused = true;
play = false;
playpause.setBackgroundDrawable(getResources().getDrawable(
R.drawable.play));
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
Button goBtn = (Button) findViewById(R.id.youtubeButton);
goBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(youTubeurl)));
}
});
ImageButton close = (ImageButton) findViewById(R.id.youtubecloseButton);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
frameLayout.setVisibility(View.GONE);
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
playpause.setBackgroundDrawable(getResources().getDrawable(
R.drawable.pause));
}
});
}
} else {
Toast.makeText(getApplicationContext(), "No network available", Toast.LENGTH_SHORT).show();
}
} else {
frameLayout.setVisibility(View.INVISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
return;
}
Here whenever, if (convSeconds == youTubeStartTime) {} becomes true, I am making my audio pause i.e.,
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
And during this time also I want the start() inside Runnable notification should be keep calling. But if I make audio pause this is not happening only. The control is completely lost in this case. And on pressing the Image button close, i am trying to make the audio again to play like this
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
Audio keeps playing now, but the slider/seekbar is not moving because start() inside notification is not getting called.
Do any one know why is it happening like this?
Note: How ever if I don make my mediaplayer not to pause, it works fine. I get the problem onky when I make the audio to pause
I solved the issue finally, it may not be the standard way. But it is working for me.
i just replicated
notification = new Runnable() {
public void run() {
start();
}
};
handler.postDelayed(notification, 1000);
where I am trying to close the image button, i.e.,
ImageButton close = (ImageButton) findViewById(R.id.youtubecloseButton);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
frameLayout.setVisibility(View.GONE);
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
notification = new Runnable() {
public void run() {
start();
}
};
handler.postDelayed(notification, 1000);
}
});

problem in using seekbar for android media player

in my app i am using media player and i want to place a seek bar there. In my code the song is playing but the seek bar is not moving. Following is the part of my code...
sv = (SurfaceView)findViewById(R.id.surfaceView1);
sv.postDelayed(runnable,200);
final Runnable runnable = new Runnable()
{
#Override
public void run()
{
if (mediaPlayer != null)
{
if (isPlaying)
{
try
{
int currentPosition = mediaPlayer.getCurrentPosition();
audioProgress.setProgress((int) ((currentPosition / (float) mediaPlayer.getDuration()) * 100f));
} catch (Exception e) {
e.printStackTrace();
}
sv.postDelayed(runnable, 150);
}
}
}
};
Please anyone help me in clearing the errors...
Make these changes to your code:
sv = (SurfaceView)findViewById(R.id.surfaceView1);
audioProgress.setMax(mediaPlayer.getDuration()); // this is one change
sv.postDelayed(runnable,200);
final Runnable runnable = new Runnable()
{
#Override
public void run()
{
if (mediaPlayer != null)
{
if (isPlaying)
{
try
{
int currentPosition = mediaPlayer.getCurrentPosition();
// the other change:
audioProgress.setProgress(currentPosition);
} catch (Exception e) {
e.printStackTrace();
}
sv.postDelayed(runnable, 150);
}
}
}
};

Categories

Resources