How to run code any 3000m/s in android - android

I write below method and i want run this method any 3000M/S
public void onShakeImage() {
Animation shake;
shake = AnimationUtils.loadAnimation(context, R.anim.shake);
arrowHelpImage.setAnimation(shake);
}
how can i do it?

private Handler mHandler;
#Override
protected void onCreate(Bundle bundle) {
mHandler = new Handler();
startRepeatingTask();
}
#Override
public void onDestroy() {
super.onDestroy();
stopRepeatingTask();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
try {
onShakeImage(); //this function can change value of mInterval.
} finally {
mHandler.postDelayed(mStatusChecker, 3000);
}
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}

Related

Android update ProgressBar with Handler

I would like to update the progressBar with Handler and for loop but without success.
Code:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(progress_k, 100);
}
}, 2000);
}
}
Question:
The progress bar increase immediately to the end value instead of progressively.
Why?
Try this:
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler(Looper.getMainLooper());
for (progress_k = from; progress_k<=to ;progress_k++)
{
final int curr_progress_k = progress_k;
handler1.postDelayed(new Runnable()
{
#Override
public void run()
{
FrontLayout.update_splash_progress_bar(curr_progress_k, 100);
}
}, progress_k * 100); // adjust "100" value to adjust speed
}
}
Repeat a task with a time delay?
#inazaruk
private ProgressBar progressBar;
private Handler mHandler;
private int progressInt = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
progressBar = (ProgressBar) findViewById(R.id.pb);
progressBar.setProgress(0);
mHandler = new Handler();
runnable.run();
}
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
updateProgress();
} catch (Exception ignored) {
} finally {
mHandler.postDelayed(runnable, progressInt);
}
}
};
private void updateProgress() {
progressInt += 1;
if (progressInt > 100) {
mHandler.removeCallbacks(runnable);
} else {
progressBar.setProgress(progressInt);
}
}
try this code:
Solution 1
public void increase_splash_bar (int from, int to)
{
Handler handler1 = new Handler();
class Task implements Runnable {
int start,end;
Task(int a,int b) { start = a; end = b;}
#Override
public void run() {
for (int i =start ; i <= end; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler1.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(value);
}
});
}
}
}
Thread t = new Thread(new Task(from, to)); //call it
t.start();
}
Solution 2: More Simple
If thread is too much to ask for this problem..
you can use the following solution to use a single Handler to update progressbar:
code
public class HandlerDemo extends Activity
{
ProgressBar bar;
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
bar.incrementProgressBy(5);
}
};
boolean isRunning = false;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progress);
}
public void onStart()
{
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable()
{
public void run()
{
try
{
for (int i = 0; i < 20 && isRunning; i++)
{
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t)
{
// just end the background thread
}
}
});
isRunning = true;
background.start();
}
public void onStop()
{
super.onStop();
isRunning = false;
}
}
Hope it helps..

How to stop the thread in Android?

I have a thread in my callback function as follows:
#Override
public void onConnectError(final BluetoothDevice device, String message) {
Log.d("TAG","Trying again in 3 sec.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something
}
}, 2000);
}
});
}
I will to close the the above thread when I press the back button or onDestroy. How can I do it. Thank you
#Override
public void onBackPressed() {
// Close or distroy the thread
}
#Override
public void onDestroy() {
// Close or distroy the thread
}
Please do this like
private Handler handler;
private Runnable runnable;
#Override
public void onConnectError(final BluetoothDevice device, String message) {
Log.d("TAG","Trying again in 3 sec.");
runOnUiThread(new Runnable() {
#Override
public void run() {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
//Do something
}
};
handler.postDelayed(runnable, 2000);
}
});
}
and
#Override
public void onBackPressed() {
if (handler != null && runnable != null) {
handler.removeCallbacks(runnable);
}
}
and same in onDestroy();
I'm mostly use thread in this way.See its independent in activity
public class TestActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
holdConnectionHandler.sendEmptyMessage(0);
}
Handler holdConnectionHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
// do some work
holdConnectionHandler.sendEmptyMessageDelayed(0, 10 * 1000);
}
};
#Override
public void onDestroy() {
super.onDestroy();
holdConnectionHandler.removeCallbacksAndMessages(null);
// or
holdConnectionHandler.removeMessages(0);
}
}
Thanks hope this will help you

bar.setProgress(0) does not work

The following code is from Beginning Android 3, Chapter 20. When the phone is rotated, a new activity will be created and onStart() will be called, and so bar.setProgress(0) is called. However, I don't see the bar's progress is back to the beginning. Why not?
public class HandlerDemo extends Activity {
ProgressBar bar;
Handler handler=new Handler() {
#Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
}
};
AtomicBoolean isRunning=new AtomicBoolean(false);
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
bar=(ProgressBar)findViewById(R.id.progress);
}
public void onStart() {
super.onStart();
bar.setProgress(0);
Thread background=new Thread(new Runnable() {
public void run() {
try {
for (int i=0;i<20 && isRunning.get();i++) {
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
} catch (Throwable t) {
// just end the background thread
}
}
});
isRunning.set(true);
background.start();
}
public void onStop() {
super.onStop();
isRunning.set(false);
}
}
Try using this code
#Override
protected void onPause() {
super.onPause();
isRunning.set(false);
bar.setProgress(0);
}

How do I update a ProgressBar using a Handler?

I'm new to Android and I'm trying to work through a tutorial on using a ProgressBar in conjunction with a Handler. Just a note, I am targeting API 11.
Here is my code with the errors I am getting inline:
public class HandlerDemo extends Activity {
ProgressBar bar;
Handler handler = new Handler() {
#Override
public void handleMessage() { // Shows "method must override or implement supertype method" on this line.
bar.incrementProgressBy(5);
}
#Override
public void close() {
}
#Override
public void flush() {
}
#Override
public void publish(LogRecord arg0) {
}
};
AtomicBoolean isRunning = new AtomicBoolean(false);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_demo);
bar = (ProgressBar)findViewById(android.R.id.progress);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_handler_demo, menu);
return true;
}
public void onStart() {
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable() {
#Override
public void run() {
try {
for(int i = 0; i < 20 && isRunning.get(); i++) {
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage()); // Shows "Method is undefined for type Handler" on this line.
}
} catch(Throwable t) { }
}
});
isRunning.set(true);
background.start();
}
public void onStop() {
super.onStop();
isRunning.set(false);
}
}
Why am I getting these errors?
Your Handler import is wrong. It should be android.os.Handler

Error due to android toast message being started in the wrong thread

Hi I'm having some problems to show a toast message, actually the program crash saying that I'm trying to disply a toast in the wrong thread or something like that.
I have been reading some other questions about the topic and I think the soultions is something like using a handler to comunicate with the UI, but not sure how to do it, could any one share with me an example/tutorial about how to launch a toast mesage from any part of the code?
For example I'm trying something like this: [the problematic line is between** **]
public class SamplesTiming extends Activity {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_samples_timing);
...
}
private void setButtonHandlers() {
((Button)findViewById(R.id.btnStart)).setOnClickListener(btnClick);
((Button)findViewById(R.id.btnStop)).setOnClickListener(btnClick);
}
private void enableButton(int id,boolean isEnable){
((Button)findViewById(id)).setEnabled(isEnable);
}
private void enableButtons(boolean isRecording) {
enableButton(R.id.btnStart,!isRecording);
enableButton(R.id.btnStop,isRecording);
}
private void startRecording(){
...
recordingThread = new Thread(new Runnable() {
//#Override
public void run() {
writeAudioDataToFile();
}
},"AudioRecorder Thread");
recordingThread.start();
}
private void writeAudioDataToFile(){
...
while(isRecording){
...
read = recorder.read(data, 0, bufferSize);
if(condition) **Toast.makeText(getApplicationContext(),
"it happen", Toast.LENGTH_LONG).show();**
...
}
}
private void stopRecording(){
if(null != recorder){
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
}
private View.OnClickListener btnClick = new View.OnClickListener() {
// #Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:{
enableButtons(true);
startRecording();
break;
}
case R.id.btnStop:{
enableButtons(false);
stopRecording();
break;
}
}
}
};
}
Thank you very much for your time
It must in the main thread if you want to access the widgets.
You can write follows if you are in an Activity.
runOnUiThread(new Runnable(){
public void run(){
//toast
}
});
use Activity.runOnUiThread for showing Toast from background thread as :
while(isRecording){
......
SamplesTiming.this.runOnUiThread(new Runnable() {
public void run() {
// show toast here
Toast.makeText(SamplesTiming.this,
"it happen", Toast.LENGTH_LONG).show();
}
});
.....
}
If you are like me and you dislike convenience methods, use a Handler:
public class MainActivity extends Activity {
private Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
doSomethingOnAnotherThread();
}
private void doSomethingOnAnotherThread() {
new Thread(new Runnable() {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "toast skagen", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
}

Categories

Resources