show several Toast with delay in service - android

I want to when user click on button, start a Service.
When the service starts .
I want to show 5 times text
The delay time is 3 seconds .
show_toast1-------delay 3secounds ,
show_toast2-------delay 3secounds,
show_toast3-------delay 3secounds,.......
but when click on button Delay only occurs once!
and other show_toast is displayed without delay
java code :
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
for(int i=0;i<4;i++)
{
try {
Toast.makeText(getBaseContext(), "show_toast"+i, Toast.LENGTH_LONG).show();
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return START_STICKY;
}

Use Handler instead if Thread.sleep() , Try the code below will work for you.
public Handler handler; //global
int i = 0; //global
final Handler handler = new Handler();
runable = new Runnable() {
#Override
public void run() {
try{
//do your code here
if(i < 4){
Toast.makeText(MainActivity.this, "show_toast"+i, Toast.LENGTH_LONG).show();
i = i + 1;
//also call the same runnable
handler.postDelayed(this, 5000);
}
else{
handler.removeCallbacks(runable);
}
}
catch (Exception e) {
// TODO: handle exception
}
}
};
handler.postDelayed(runable, 5000);

Related

Infinite IntentService stops working when there is no breakpoint

I have got an infinite IntentService meant to enable scanner for all the time application is alive. And whenever there is a breakpoint - it works fine. But when I remove a breakpoint from a loop - it stops working after some time. And then again when I put a breakpoint - it starts working again. What the heck? How can I fix this?
protected void onHandleIntent(#Nullable Intent intent)
{
final Handler handler = new Handler();
handler.post(new Runnable()
{
#Override
public void run()
{
while(true)
{
if (!blocked)
{
blocked = true;
String received = GlobalAccess.scan.scan(1000);
if (received != null && !received.isEmpty())
{
//TODO: some stuff here
}
blocked = false;
}
else
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
});
}
EDIT
I have created my CustomService with
#Override
public void onCreate()
{
super.onCreate();
scheduledExecutorService = Executors.newScheduledThreadPool(1);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
final Handler handler = new Handler();
Runnable runnable = new Runnable()
{
#Override
public void run()
{
while(true)
{
if (!blocked)
{
blocked = true;
String received = GlobalAccess.scan.scan(1000);
if (!Objects.equals(received, null) && !received.isEmpty())
{
//TODO: some stuff here
}
blocked = false;
}
else
{
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
}
};
ScheduledFuture scheduledFuture = scheduledExecutorService.schedule(runnable, 0, TimeUnit.MILLISECONDS);
return START_STICKY;
}
But it has exact same bahavior as IntentService
Thanks to #CommonsWare I have managed to solve my problem.
This is the solution:
public class ScanService extends Service
{
ScheduledExecutorService scheduledExecutorService;
#Override
public void onCreate()
{
super.onCreate();
scheduledExecutorService = Executors.newScheduledThreadPool(1);
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
String received = GlobalAccess.scan.scan(1000);
if (!Objects.equals(received, null) && !received.isEmpty())
{
//TODO: some stuff here
}
}
};
scheduledExecutorService.scheduleWithFixedDelay(runnable, 0, 50, TimeUnit.MILLISECONDS);
return START_STICKY;
}
}

ProgressDialog doesn't appear when calling a thread inside AsyncTask

I have an app that sends a file through a socket. While doing this I want to show the progress in a ProgressDialog. The app sends the file perfectly but I'm not able to make the dialog appear.
public class ProgressDialogActivity extends Activity {
private ProgressDialog downloadDialog = null;
private String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
filePath = getIntent().getExtras().getString("filePath");
downloadDialog = new ProgressDialog(this);
Task myTask = new Task();
myTask.execute(0);
}
private void showMessage(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), msg, `enter code here`Toast.LENGTH_SHORT).show();
}
});
}
private class Task extends AsyncTask<Integer, Integer, Boolean> implements Observer
{
private Thread t;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
downloadDialog.setTitle("SENDING");
downloadDialog.setMessage("................");
downloadDialog.setCancelable(false);
downloadDialog.setIndeterminate(false);
// downloadDialog.setMax(100);
downloadDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
downloadDialog.show();
}
#Override
protected Boolean doInBackground(Integer... params) {
SendFile send = new SendFile(filePath);
downloadDialog.setMax(0);
t = new Thread(send);
send.registerObserver(this);
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
t.start();
return true;
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
int counter = values[0].intValue();
downloadDialog.setProgress(counter);
if(filePath != null)
{
downloadDialog.setMessage(filePath+"...");
}
}
#Override
public void update(Subject subject) {
// TODO Auto-generated method stub
if(subject instanceof SendFile)
{
SendFile e = (SendFile) subject;
if(e.getException() != null)
{
t.interrupt();
showMessage(e.getException());
} else
{
if(!e.isStarted())
{
initializeProgressBar(e.getNumIter());
} else
{
refreshProgressBar(e.getNumIter());
}
if(e.isSent())
{
t.interrupt();
showMessage("File sent");
}
}
}
}
public void initializeProgressBar(int max){
downloadDialog.setMax(max);
}
public void refreshProgressBar(int amount){
publishProgress(downloadDialog.getMax()-amount);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(downloadDialog != null)
{
downloadDialog.dismiss();
}
finish();
}
#Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
t.interrupt();
showMessage("TASK CANCELLED");
}
};
}
SendFile is the class that contains the socket to send the files.
I think the problem is due to I'm calling the thread inside the AssyncTask because when I make Thread.sleep(10000) I can see the ProgressDialog for that time, but I don't know how to fix it.
Also, when I run the debugger I can see that the variable 'counter' is incremented every time I call it, but if I add a watch with 'downloadDialog.getProgress()' the progress is always 0.
You are creating an AsyncTask, which doInBackground() method RUNS IN BACKGROUND. In there, you don't do anything, but start a new thread... Now this thread does the work, but your AsyncTask finishes, because it has nothing to do after starting the other thread... So, your ProgressDialog is shown for some milliseconds, then your AsyncTask finishes and the ProgressDialog is hidden again. But the thread that is doing the work is still running, only your AsyncTask has finished.
Solution : Either use an AsyncTask OR use a thread.
You need to call publishProgress on doinBackground()
Example:
protected String doInBackground(Void... params) {
try {
int i = 0;
Log.i("Thread","1");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","2");
Thread.sleep(1000);
publishProgress(i++);
Log.i("Thread","3");
Thread.sleep(1000);
Log.i("Thread","4");
Thread.sleep(1000);
Log.i("Thread","5");
} catch (InterruptedException e) {
e.printStackTrace();
}
return "done";
}

Error in running a thread from inside a timertask (running inside a Thread) present in a Service

I have a Service which runs a thread. This thread runs a timertask, this timertask now has to run another thread.
My Service class looks like this:
Timer pTimer;
int Time = 1;
int samplerate=100;
int sampleSize=((Time*1000)/samplerate);
Accelerometer_Thread Ac_Thread;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
pTimer = new Timer();
Ac_Thread = new Accelerometer_Thread();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO Auto-generated method stub
//super.onStart(intent, startId);
Ac_Thread.start();
return START_STICKY;
}
public class Accelerometer_Thread extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
pTimer.scheduleAtFixedRate(task,0, samplerate);
}
}
/* The Timertask which is to be executed at a periodic interval of "samplerate" */
TimerTask task = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
String Ack = null;
try {
Ack = Post.PostToWebService("Hello");
} catch (Exception e) {
// TODO Auto-generated catch block
}
if (Ack.contentEquals("1")) {
//Do SOmething
}
else
Log.d("Error", "NotSent To Webservice");
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
};
The Post.PostToWebService which starts the Thread looks like this:
public static String ReceivedAcknowledgement=null;
public static String buffer;
public static String PostToWebService(String Payload){
CallPost cp = new CallPost();
buffer = Payload;
ReceivedAcknowledgement="STRT";
try {
cp.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cp.start();
while(ReceivedAcknowledgement=="STRT")
{
try
{
Thread.sleep(10);
}catch(Exception ex)
{
}
}
if(ReceivedAcknowledgement != "STRT")
return ReceivedAcknowledgement;
else
return null;
}
The CallPost looks like this:
public class CallPost extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
Post.ReceivedAcknowledgement = ParseXML(in);
}
private String ParseXML(InputStream i){
//Parse
}
}
I'm getting an error in my Service class at the line Post.PostToWebService("Hello") where the error says:
java.lang.RuntimeException: Can't create handler inside thread that
has not called Looper.prepare()
I've tried understanding about loopers and handlers but I'm not able to get it.

I am trying to block facebook on system browser

For this,first i am getting the top activity from the stack and then matching the string of Facebook in logcat..
I am using this Code,
public class MyService extends Service
{
public static String Tag = "Task";
public static String Tag1 = "Top Running Task";
ActivityManager am ;
String packageName ;
Handler handler;
int count=0;
#Override
public int onStartCommand(Intent intent,int flags, int startId)
{
// TODO Auto-generated method stub
super.onStartCommand(intent, flags,startId);
Toast.makeText(this, "Service running", Toast.LENGTH_SHORT).show();
handler = new Handler(){
#Override
public void handleMessage(Message msg)
{
// TODO Auto-generated method stub
super.handleMessage(msg);
// Browser.clearHistory(getContentResolver());
//Browser.clearSearches(getContentResolver());
String packageName = am.getRunningTasks(1).get(0).topActivity.getPackageName();
if((packageName).indexOf("browser")!= -1)
{
// Toast tost=Toast.makeText(getApplicationContext(), packageName.toString(), 1);
//tost.show();
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
if(line.contains("facebook.com"))
{
//Browser.addSearchUrl(getContentResolver(), "google");
Log.i(Tag1,"ww"+ line);
/*Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);*/
//android.os.Process.killProcess(pid);
}
//log.;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//}
}
};
new Thread(new Runnable()
{
public void run()
{
while(true)
{
try
{
Thread.sleep(1000);
handler.sendEmptyMessage(0);
}
catch (InterruptedException e) {}
}
}
}).start();
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
super.onDestroy();
am.killBackgroundProcesses(packageName);
Log.i(Tag,"destory ");
}
#Override
public IBinder onBind(Intent intent)
{
//TODO for communication return IBinder implementation
return null;
}
}
I am deleting the History and cache too.
After that,i am able to block facebook but first time,it works fine but second time it does not work,it keeps its history for 5-6 seconds and after that again worked fine.

Launching already running activity from service intent

RE: Move back to App after launching another App
and Launching Intent from service causes crash
I now have the terminal launching correctly from my service, however my next step is to, after the service has launched the terminal intent to relaunch the apps main activity.
I am doing this using:
public void backtoEmplayer(){
Intent intenti = new Intent(MainService.this,MainActivity.class);
intenti.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intenti.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intenti);
}
So that it will simply bring forward the main activity which should still be running (As the only two things ever launched on this device will be my app and the terminal).
However when I run the above code I get the following error:
E/AndroidRuntime (1859): FATAL EXCEPTION: Thread-931
E/AndroidRuntime (1859): android.util.AndroidRuntimeException: Calling startActvitiy() from outside of an Activity context requires the FLAT_ACTIVITY_NEW_TASK flas. Is this really what you want?
E/AndroidRuntime (1859): at android.app.ContextImpl.startActivity(ContextImpl.java:864)
E/AndroidRuntime (1859): at android.content.ContentWrapper.startActivity(ContextWrapper.java 276)
E/AndroidRuntime (1859): at packagename.MainService.backtoEmplayer(MainService.java:187)
What I do not understand is that fact that I am using the FLAT_ACTIVITY_NEW_TASK flag but it still does not work.
My complete service class now looks like:
public class MainService extends Service {
boolean copied = false;
private String mHandle;
private static final int REQUEST_WINDOW_HANDLE = 1;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startId) {
Thread usbUpdateThread = new Thread() {
public void run() {
while (true) {
while (!copied) {
try {
Thread.sleep(180000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
runCommand("chmod -R 777 /media/cdrom/");
copied = false;
}
}
};
Thread InternetThread = new Thread() {
public void run() {
while (true){
try {
Thread.sleep(3600000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runCommand("php update.php");
}
}
};
Thread CheckThread = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(300000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runCommand("sh check.sh");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
backtoEmplayer();
}
}
};
InternetThread.start();
CheckThread.start();
usbUpdateThread.start();
}
public boolean runCommand(String command) {
Intent intent = new Intent("jackpal.androidterm.RUN_SCRIPT");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("jackpal.androidterm.iInitialCommand", command);
intent.putExtra("jackpal.androidterm.window_handle", MainActivity.mHandle);
startActivity(intent);
return true;
}
public void backtoEmplayer(){
Intent intenti = new Intent(MainService.this,MainActivity.class);
intenti.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intenti.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intenti);
}
}
Remove
intenti.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
from your code.

Categories

Resources