Is there a way to refresh webView every x seconds? - java

Now I have this function for reload webView:
public void reloadWebView() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
webView.reload();
}
}, 5000);}
And it is called on onCreate function
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reloadWebView();
}
The function works but it only runs once

Easy to solve as long as the Activity is running in foreground:
Handler handler = new Handler();
public void reloadWebView() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
webView.reload();
reloadWebView();
}
}, 5000);}
Note that handler is now a field, out of reloadWebView().
Now call it in your onCreate():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
reloadWebView();
}

Here is code to update your webview after x seconds
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
webView.reload();
//here you can have your logic to reload webview
}
public void onFinish() {
// hide progress bar if any
}
}.start();

Related

Android app to play mp3 file in specific time with countdown timer

I was trying to create an android app that should get time in minutes from a seek bar then it should begin to play a sound file until the countdown timer ends.
Things are mostly fine with the countdown timer BUT my question is how should I call some methods of the countdown timer instance when a button is pressed.
In the code below, I want to call onFinish() whenever the stop button pressed.
Here is my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SeekBar sb = (SeekBar) findViewById(R.id.seekBar);
Button bt_stop = (Button) findViewById(R.id.btn1);
final TextView tv = (TextView)findViewById(R.id.textView);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
int millisec_time = (i*60)/1000;
new CountDownTimer(millisec_time, 1000) {
public void onTick(long millisUntilFinished) {
tv.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
tv.setText("done!");
}
}.start();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Toast.makeText(getApplicationContext(),"GOT",Toast.LENGTH_LONG).show();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Toast.makeText(getApplicationContext(),"OFF",Toast.LENGTH_LONG).show();
}
});
bt_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
}
First, I'd recommend you only start your CountdownTimer in onStopTrackingTouch - reason being that currently you're creating a brand new timer every time the progress changes on your seekbar (which could be happening a lot).
Secondly, you'll need to retain a reference to your timer in order to cancel it. So:
public class MainActivity extends AppCompatActivity {
private CountdownTimer timer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SeekBar sb = (SeekBar) findViewById(R.id.seekBar);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
restartTimer(seekBar);
}
}
final Button bt_stop = (Button) findViewById(R.id.btn1);
bt_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(timer != null) {
timer.cancel();
}
}
});
}
private void restartTimer(SeekBar sb) {
if(timer!=null) {
timer.cancel();
}
final long millis = TimeUnit.SECONDS.toMillis(sb.getProgress());
final long interval = TimeUnit.SECONDS.toMillis(1);
timer = new CountdownTimer(millis, interval) {
#Override
public void onTick(long millisUntilFinished) {
tv.setText(String.format("Seconds Remaining: %d", TimeUnit.MILLIS.toSeconds(millisUntilFinished));
}
#Override
public void onFinish() {
tv.setText("done!");
}
}
timer.start();
}
}

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

ProgressDialog in runOnUiThread

I am trying to show progress dialog and update it inside runOnUiThread
but the progress bar never shown. when I replace the runOnUiThread with "new Thread" it work fine. But I want it to work with runOnUiThread
here is my code , I have deleted unnecessary codes
public class test extends Activity {
private ProgressDialog progress;
Handler progressBarHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
testing();
}
public void testing() {
progress=new ProgressDialog(this);
progress.setMessage("Saving Progress");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(100);
progress.setCancelable(false);
progress.show();
runOnUiThread(new Runnable() {
#Override
public void run() {
//do some work
for (int i =0; i<100;i++){
//some work
progressBarHandler.post(new Runnable() {
#Override
public void run() {
progress.setProgress(finalCount);
}
});
}
}
}
Try this
public class MainActivity extends AppCompatActivity {
private ProgressDialog progress;
Handler workHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress=new ProgressDialog(this);
progress.setMessage("Saving Progress");
progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progress.setProgress(0);
progress.setMax(100);
progress.setCancelable(false);
progress.show();
workHandler = new Handler(new HandlerThread("workHandlerThread").getLooper());
workHandler.post(new Runnable() {
#Override
public void run() {
//Do some work
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.setProgress(/*work result*/);
}
});
}
});
}
}
The idea is you do the work on the HandlerThread bound to workHandler, and post the results back the the UI using runOnUiThread()

Timer() function not working when going to another activity

In my application i want to close it after 5 seconds using Timer() function.It works when i am in MainActivity but when i go to another activity then the application do not close.Now how to run this Timer() function in background if i switch activity.What to do in this case?
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
finish();
}
}, 5000); // Application will be closed after 5 seconds
You achieve this using broadcast receiver. in your activity which you want to finish you need to create broadcast receiver.
public class TestActivity extends Activity {
public static String intent_filter_finish = "com.test.finish";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
registerReceiver(finishReceiver,
new IntentFilter(intent_filter_finish));
}
#Override
protected void onDestroy() {
unregisterReceiver(finishReceiver);
super.onDestroy();
}
BroadcastReceiver finishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
}
now in your second activity you need to send broadcast after 5 second e.g.
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
sendBroadcast(new Intent(TestActivity.intent_filter_finish));
}
}, 5000);
}
}
or other possible way is directly use postDelayed() method in your test activity e.g.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
finish();
}
}, 5000);

calling another activity function inside an activity via handler doesn't work

I want to start a CountDownTimer from another activity. I use handlers to do that, but it doesn't work. Which part am I doing wrong? This is my code:
activity1.java :
public class Activity1 extends Activity {
public static Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initHandler();
mHandler.sendEmptyMessage(1);
startActivity(new Intent(Activity1.this, Activity2.class));
}
private void initHandler(){
mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch (msg.arg1) {
case 1:
mCountDownTimer.start();
break;
}
}
};
}
private CountDownTimer mCountDownTimer = new CountDownTimer(10000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Toast.makeText(Activity1.this, "Count is: "+ millisUntilFinished/1000, Toast.LENGTH_SHORT).show();
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
};
}
activity2.java :
public class Activity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Activity1.mHandler.sendEmptyMessage(1);
}
}
Why is this not working?
In your initHandler() method, change your condition in switch case from switch (msg.arg1) to switch (msg.what)
According to Android Developer site sendEmptyMessage(int) Sends a Message containing only the what value.

Categories

Resources