How to display toast inside timer? - android

I want to display toast message inside timer and I used the following code :
timer.scheduleAtFixedRate( new TimerTask()
{
public void run()
{
try {
fun1();
} catch (Exception e) {e.printStackTrace(); }
}
}, 0,60000);
public void fun1()
{
//want to display toast
}
And I am getting following error:
WARN/System.err(593): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
WARN/System.err(593): at android.os.Handler.(Handler.java:121)
WARN/System.err(593): at android.widget.Toast.(Toast.java:68)
WARN/System.err(593): at android.widget.Toast.makeText(Toast.java:231)
Thanks.

You can't make UI updates inside separate Thread, like Timer. You should use Handler object for UI update:
timer.scheduleAtFixedRate( new TimerTask() {
private Handler updateUI = new Handler(){
#Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
fun1();
}
};
public void run() {
try {
updateUI.sendEmptyMessage(0);
} catch (Exception e) {e.printStackTrace(); }
}
}, 0,60000);

The easiest way (IMO) is:
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
final String message = "Hi";
MyActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MyActivity.this, message, Toast.LENGTH_SHORT).show();
}
});
}
});
The key being MyActivity.this.runOnUiThread(Runnable).

create a Handler and display toast in this
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
// Toast here
}
};

You need access to the Context of the application to be able to do this. Try creating your own class which takes the context as input parameter:
private class MyTimerTask extends TimerTask {
private Context context;
public MyTimerTask(Context context) {
this.context = context;
}
#Override
public void run() {
Toast.makeText(context, "Toast text", Toast.LENGTH_SHORT).show();
}
}
Then in your timer:
timer.scheduleAtFixedRate( new MyTimerTask(this), 0,60000);

I wanted to make a simple project that could display a Toast in a Timer.
The Timer would be started using a service. Then, the Timer starts when the service is started and stops when service is stopped.
Class 1
package com.example.connect;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button button1,button2;
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
}
public void Start(View v)
{
startService(new Intent(MainActivity.this , Connect_service.class));
}
public void Stop(View v)
{
stopService(new Intent(MainActivity.this , Connect_service.class));
}
}
Class 2
package com.example.connect;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Connect_service extends Service{
Timer timer = new Timer();
TimerTask updateProfile = new CustomTimerTask(Connect_service.this);
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
timer.scheduleAtFixedRate(updateProfile, 0, 5000);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
timer.cancel();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Class 3
package com.example.connect;
import java.util.TimerTask;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
public class CustomTimerTask extends TimerTask {
private Context context;
private Handler mHandler = new Handler();
public CustomTimerTask(Context con) {
this.context = con;
}
#Override
public void run() {
new Thread(new Runnable() {
public void run() {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(context, "In Timer", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
}

I'm trying to make my own toast with my own views.
I've successfully combined your approaches. The following code allows me to show toasts and change/remove views without crashing, just change the parameters of the MyTimerTask constructor to whatever you need to work on.
public void yourFunction(){
Timer timer = new Timer();
MyTimerTask mtc = new MyTimerTask(this.getContext(), tvNotice);
timer.schedule(mtc, 1000);
}
private class MyTimerTask extends TimerTask {
private TextView tv;
private Context context;
public MyTimerTask(Context pContext, TextView pTv) {
this.tv = pTv;
this.context = pContext;
}
#Override
public void run() {
updateUI.sendEmptyMessage(0);
}
private Handler updateUI = new Handler(){
#Override
public void dispatchMessage(Message msg) {
super.dispatchMessage(msg);
tv.setText("TextView Message");
Toast.makeText(context, "Toast Message", 0).show();
}
};
}

You have to call UIThread for showing Toast, not from timer thread.
Else call UI thread from that timer thread.
This link will help you,
http://developer.android.com/resources/articles/timed-ui-updates.html
and this
http://developer.android.com/guide/appendix/faq/commontasks.html#threading

Related

Message is not dispatched into the thread in android

As part of my learning Android Threading, I have done the below code.
package simple.learning.com.samplethread;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
MyThread myThread;
Button button;
private static class MyThread extends Thread {
public Handler mHandler;
public void run () {
Log.d ("TESTME", " iNSIDE RUN..");
Looper.prepare();
mHandler = new Handler () {
public void HandleMessage (Message msg) {
Log.d("TESTME", "iNSIDE HandleMessage");
if ( msg.what == 0) {
someWork();
}
}
};
Looper.loop();
}
public void someWork()
{
while (true) {
Log.d("TESTME", "Inside someWork ");
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myThread = new MyThread();
myThread.start();
Button btn = (Button) findViewById(R.id.button1);
assert btn != null;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myThread.mHandler != null) {
Log.d("TESTME", " bUTTON pRESSED..");
Message msg = myThread.mHandler.obtainMessage(0);
myThread.mHandler.sendMessage(msg);
}
}
});
}
}
When I Click the button, I expect the msg to be posted into the message queue. But, I don't see any output displayed. Any help would be appreciated.
You made a small mistake in overriding the handleMessage, instead of overriding the real one you added some method. Below is the working solution:
private static class MyThread extends Thread {
public Handler mHandler;
public void run() {
Log.d("TESTME", " iNSIDE RUN..");
Looper.prepare();
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.d("TESTME", "iNSIDE HandleMessage");
if (msg.what == 0) {
someWork();
}
}
};
Looper.loop();
}
public void someWork() {
while (true) {
Log.d("TESTME", "Inside someWork ");
}
}
}

Guarantee only one timerTasks with threads in service

My Android application has a service, that will be created at timer task with specified interval. The task should check out webservice by async task, if the Internet is enabled, send some informations, otherwise it should wait (for example, 5 seconds) and check connection again.
My problem is: how to prevent creating tasks while timertask is waiting?
I wish that at any time there is only one task working.
My code:
mTimer.scheduleAtFixedRate(new MyTask(), 0, 10000); //creating tasks in service
class MyTask extends TimerTask {
#Override
public void run() {
if (!isLocked) {
new Thread(new Runnable() {#Override
public void run() {
isLocked = true;
if (!isInternet) {
do {
Log.v("TestService", "Waiting...");
SystemClock.sleep(5000);
isInternet = getInternetConn();
} while (!isInternet);
} else {
//do work
}
isLocked = false;
}).run();
}
}
}
I would suggest you to follow this process, which i have used for getting GCM_Registration id, same as you can use it check your internet connection.
which works like : in onStartCommand(), mServiceHandler.sendMessage(msg); starts a asynctask which check does we have GCM-ID if yes we stop the service and if no, then we again check for GCM-ID by asynctask.
package com.urbanft.utils;
import java.io.IOException;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.text.TextUtils;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.urbanft.app.GlobalPreference;
public class GCMIdFetchService extends Service {
private final String SENDER_ID = "916449540455";
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private static final long INTERVAL = 1000;
private GoogleCloudMessaging mGoogleCloudMessaging;
private String mRegisterationId;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg){
new GCMIdFetchSearviceTask().execute("");
}
}
protected void initialization() {
mGoogleCloudMessaging = GoogleCloudMessaging.getInstance(getApplicationContext());
}
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("ServiceStartArguments",Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
}
class GCMIdFetchSearviceTask extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
getGCMID();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String gcmId = GlobalPreference.getInstance(getApplicationContext()).getGCMRegistrationId();
if(!TextUtils.isEmpty(gcmId)){
stopSelf();
return;
}
new Handler().postDelayed(new Runnable() {
public void run() {
Message msg = mServiceHandler.obtainMessage();
mServiceHandler.sendMessage(msg);
}
}, INTERVAL);
}
}
private void getGCMID() {
try{
if(mGoogleCloudMessaging == null){
mGoogleCloudMessaging = GoogleCloudMessaging.getInstance(getApplicationContext());
}
mRegisterationId = mGoogleCloudMessaging.register(SENDER_ID);
GlobalPreference.getInstance(getApplicationContext()).setGCMRegistrationId(mRegisterationId);
}
catch (IOException err){
err.printStackTrace();
}
}
}

IntentService Thread.sleep() limit?

i was wondering if the IntentService has thread blocking limit like calling Thread.sleep(); and if so what's the maximum time limit for it?
so i wrote the following code snippet:
package net.yassin.aaaservice;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.SystemClock;
import android.widget.Toast;
public class MyService extends IntentService {
private Thread t;
private static int i = 0;
private static final int SLEEP_DURATION = 2000;
private Handler handler;
public MyService() {
super("MyService");
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
this.handler = new Handler();
}
#Override
protected void onHandleIntent(Intent arg0) {
this.t = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
MyService.this.handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyService.this,
"This is toast #" + (++i),
Toast.LENGTH_SHORT).show();
}
});
try {
Thread.sleep(SLEEP_DURATION);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
this.t.start();
}
}
and i found that whenever i change the time SLEEP_DURATION constant to over than 2000 Milis the service will stop showing Toasts if i removed the app form the recent menu?
am i right or there is another time limit or behavior ?
thnx :)

how can show toast from service every 10 seconds

I have an android application and I want to show a notification or toast every 10 seconds for example from Service when application is closed or finished
I have provided below a sample activity, a service class and a Timer class. use similar implementation in your application.
Activity Class
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
public class Sample extends Activity {
Button button1,button2;
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call the start and stop method when needed.
}
public void Start(View v)
{
startService(new Intent(MainActivity.this , Sample_service.class));
}
public void Stop(View v)
{
stopService(new Intent(MainActivity.this , Sample_service.class));
}
}
Service Class
package com.example.connect;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Sample_service extends Service{
Timer timer = new Timer();
TimerTask updateProfile = new CustomTimerTask(Sample_service.this);
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
timer.scheduleAtFixedRate(updateProfile, 0, 10000);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
timer.cancel();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Timer class
package com.example.connect;
import java.util.TimerTask;
import android.content.Context;
import android.os.Handler;
import android.widget.Toast;
public class CustomTimerTask extends TimerTask {
private Context context;
private Handler mHandler = new Handler();
public CustomTimerTask(Context con) {
this.context = con;
}
#Override
public void run() {
new Thread(new Runnable() {
public void run() {
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(context, "DISPLAY YOUR MESSAGE", Toast.LENGTH_SHORT).show();
}
});
}
}).start();
}
}
I have given here three files,MainActivity,Manifest and MyService file implement it in your application and it will display toast service at every 10 seconds.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//load the layout file
startService(new Intent(this,MyService.class));//use to start the services
}
}
MyService.java
public class MyService extends Service {
public static final long INTERVAL=10000;//variable to execute services every 10 second
private Handler mHandler=new Handler(); // run on another Thread to avoid crash
private Timer mTimer=null; // timer handling
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("unsupported Operation");
}
#Override
public void onCreate() {
// cancel if service is already existed
if(mTimer!=null)
mTimer.cancel();
else
mTimer=new Timer(); // recreate new timer
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task
}
#Override
public void onDestroy() {
Toast.makeText(this, "In Destroy", Toast.LENGTH_SHORT).show();//display toast when method called
mTimer.cancel();//cancel the timer
}
//inner class of TimeDisplayTimerTask
private class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast at every 10 second
Toast.makeText(getApplicationContext(), "Notify", Toast.LENGTH_SHORT).show();
}
});
}
}
}
AndroidManifest.xml
<service android:name=".MyService"
android:enabled="true"/>
Technically, When task is executed which you wrote in onCreate() method, It automatically close. For this you can use timer/scheduler.
Example :
Timer timer;
TimerTask timerTask;
timer.schedule(timerTask, 5000, 10000);
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
Toast toast = Toast.makeText(getApplicationContext(), strDate, duration);
toast.show();
}
});
}
};
Don't forget to add your service in the manifest file inside the application Tag :
<service android:name=".ServiceGPS"
android:permission="[Add permission here if exists]"
android:label="[service name]" android:exported="true"
android:enabled="true">
</service>

Android - Toast message every 1 minute

I am trying to implement a service in Android that displays a toast message every 1 minute in Android. I am new to Android development and learned about AlarmManager that will help me do this. I have implemented the code in the following way:
This is my IIManagerActivity class
package com.example.iimanager;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.widget.Toast;
public class IIManagerActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_iimanager);
AlarmManager mgr=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(this, SampleService.class);
PendingIntent pi=PendingIntent.getService(this, 0, i, 0);
mgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), AlarmManager.INTERVAL_FIFTEEN_MINUTES/900, pi);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_iimanager, menu);
return true;
}
}
And this is my SampleService that is meant to display a toast message.
For some reason I cannot get to see a toast message no matter how long I wait.
package com.example.iimanager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class SampleService extends IntentService {
public SampleService() {
super("SimpleService");
//Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
}
#Override
protected void onHandleIntent(Intent intent) {
//do something
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
}
}
Can you please tell me what's wrong and what needs to be done to get it corrected?
Thank you very much in advance.
Copy the below 3 lines for toast call
Timer timer = new Timer();
TimerTask updateProfile = new SampleService(SampleService.this);
timer.scheduleAtFixedRate(updateProfile, 10,1000);
class CustomTimerTask extends TimerTask {
private Context context;
private Handler mHandler = new Handler();
// Write Custom Constructor to pass Context
public CustomTimerTask(Context con) {
this.context = con;
}
#Override
public void run() {
new Thread(new Runnable() {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)", Toast.LENGTH_LONG).show();
}
});
}
}).start();
}
}
Try following code,
MainActivity.java
public class MyService extends Service {
public static final long INTERVAL=60000;//variable for execute services every 1 minute
private Handler mHandler=new Handler(); // run on another Thread to avoid crash
private Timer mTimer=null; // timer handling
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("unsupported Operation");
}
#Override
public void onCreate() {
// cancel if service is already existed
if(mTimer!=null)
mTimer.cancel();
else
mTimer=new Timer(); // recreate new timer
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task
}
#Override
public void onDestroy() {
Toast.makeText(this, "In Destroy", Toast.LENGTH_SHORT).show();//display toast when method called
mTimer.cancel();//cancel the timer
}
//inner class of TimeDisplayTimerTask
private class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
mHandler.post(new Runnable() {
#Override
public void run() {
// display toast at every 1 minute
Toast.makeText(getApplicationContext(), "Notify", Toast.LENGTH_SHORT).show();
}
});
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//load the layout file
startService(new Intent(this,MyService.class));//use to start the services
}
}
Also add this code in your manifest file
AndroidManifest.xml
<service android:name=".MyService"
android:enabled="true"/>
Try to create a Timer object.Then use the scheduleAtFixedRate(TimerTask) to repeat the Toast message.
You can just make a looping thread which contains your code.
Like this:
public class Toaster extends Thread{
public void run(){
//Your code to loop
thread.sleep(60000)
}
}
Hope it helps!

Categories

Resources