Android : android: with delay in thread

on Friday, September 12, 2014


i'm new in android. i made an app with service and thread to show a Toast every 5 seconds:



import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
Handler mHandler = new Handler();

@Override
public void onCreate() {
super.onCreate();

final Runnable RunnableUpdateResults = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), "Hello", Toast.LENGTH_SHORT).show();
}
};
new Thread() {
public void run() {
try {
mHandler.postDelayed(RunnableUpdateResults);
sleep(5000);
} catch (InterruptedException e) {e.printStackTrace();}
}
}.start();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
}

public void onStart(final Context context,Intent intent, int startId)
{
}
}


but my Toast shown only once. with no crash. i used Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls but it dose not work too.


any solution to do a task repetitively ?


0 comments:

Post a Comment