I continue to receive messages after Activity is destroyed - android

Hi everybody and Merry Christmas.
Please see this snippet of code.
As you can see there is an Handler that receives messages form a Service.
When the Activty is destroyed, I take care of destroying the Service, nevertheless it seems like the Service is still sending back messages to the Handler (which I don't think it is the case).
For some reason the Handler seems to stay alive and post:
Log.e("","MESSAGGIO RICEVUTO");
like it is continuing to receive messages.
Thanks for your help!!!
private String url;
private String url2;
private WebView browser;
private HttpClient client;
private List<Forecast> forecasts=new ArrayList<Forecast>();
public String responseBody;
public ArrayList<Stock> lt;
public LocalService mService;
boolean mBound = false;
public MyAdapter myAdap;
public Messenger messenger;
public Grab g;
public Handler handler;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
url2=getString(R.string.url2);
Log.e("", "arrivo a prima di forecast");
g = new Grab(url2);
String s = g.vai();
Log.e("", s);
Log.e("", "passo oltre l'invocazione al grab");
lt = new MyParser(s).parseResp();
ListView lv = (ListView)findViewById(android.R.id.list);
myAdap= new MyAdapter(lt, this);
lv.setAdapter(myAdap);
lv.setOnItemClickListener(new myListener());
handler=new Handler() {
#Override
public void handleMessage(Message msg) {
Log.e("","MESSAGGIO RICEVUTO");
lt = mService.ritira();
myAdap.notifyDataSetChanged();
g.fermaGrab();
}
};
messenger = new Messenger(handler);
}
This is the Service:
public class LocalService extends Service {
public Messenger messenger;
public int i;
public ArrayList<Stock> al;
public DefaultHttpClient client;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
public Task t;
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
// Return this instance of LocalService so clients can call public methods
return LocalService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
Log.e("", "sono nel service");
messenger = (Messenger) intent.getExtras().get("messenger");
return mBinder;
}
class Task extends AsyncTask<Void, String, Void> {
#Override
protected Void doInBackground(Void... unused) {
Log.e("Sono nel AsyncTask del Service", Integer.toBinaryString(i));
/////////INIZIA IL CASINO
client=new DefaultHttpClient();
for(int in=0;;in++)
{
for(int i=0;i<al.size();i++)
{
String srt="";
String url =getString(R.string.dettaglio1).concat("'"+al.get(i).simbolo+"'").concat(getString(R.string. dettaglio2));
HttpGet getMethod=new HttpGet(url);
try {
ResponseHandler<String> responseHandler=new BasicResponseHandler();
srt=client.execute(getMethod, responseHandler);
//Log.e("", "passo per GrabXML");
int inizio = srt.indexOf("<company data=\"");
int fine = srt.indexOf("\"/>",inizio+15);
String s =srt.substring(inizio+15,fine).substring(0, 10);
al.get(i).setNome(s);
Log.e("",al.get(i).nome);
//Log.e("",Integer.toString((al.get(i).nome.length())));
inizio = srt.indexOf("<last data=\"");
fine = srt.indexOf("\"/>",inizio+12);
al.get(i).setPrezzo(srt.substring(inizio+12,fine));
//Log.e("",Float.toString(al.get(i).prezzo));
inizio = srt.indexOf("<perc_change data=\"");
fine = srt.indexOf("\"/>",inizio+19);
al.get(i).setCambiamento(srt.substring(inizio+19,fine));
//Log.e("",Float.toString(al.get(i).cambiamento));
}
catch (Throwable t) {
android.util.Log.e("grabXML", "Exception fetching data", t);
}
}
/////////INIZIA IL CASINO
Collections.sort(al, new Comparator<Stock>(){
public int compare(Stock s1, Stock s2) {
return s1.nome.compareToIgnoreCase(s2.nome);
}
});
Message msg=Message.obtain();
try {
messenger.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SystemClock.sleep(6000);
}
/////////FINISCE IL CASINO
}
#Override
protected void onProgressUpdate(String... unused) {
}
#Override
protected void onPostExecute(Void unused) {
}
}
public void stop() {
Log.e("", "passo per lo stop del Service");
t.cancel(true);
client.getConnectionManager().shutdown();
return;
}
}
I shut down the Service on the main Activity in the onDestroy():
protected void onDestroy() {
Log.e("ondestroy","passo per ondestroy");
//handler.removeMessages();
mService.stop();
g.fermaGrab();
handler.removeMessages(333);
//g=null;
super.onDestroy();
}

You're continuing receiving a message from your service because of this infinite loop
class Task extends AsyncTask<Void, String, Void> {
#Override
protected Void doInBackground(Void... unused) {
for (int in = 0;; in++) {
// .. Other definition
Message msg = Message.obtain();
try {
messenger.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SystemClock.sleep(6000);
}
}
}
A conditionless for-loop is doing an infinite process, so your service's thread is still sending you a message right?
Just put !isCancelled() in your loop, and you can now stop your loop and Asynctask
for (int in = 0; !isCancelled() ; in++) {
// ...
}

Please see this. It is not answer to your question. It will help you to get answer,
How to stop the handler?

Related

My service shutsdown when acticty exits and unbinds to it, would like it to keep running

I'm trying to creat a bacckground service that will have a thread that adds one to a counter every minute.
I want other apps to be able to call a methed call getBot that will retunt the value.
Right now I have a test app that has a activty that bindss to the app so it can talk to it to get the counter. When it exits it unbounds to it.
It has a button called botGert that gets the current counter value from the service.
When it unbounds to it, the service shuts down. How can I get it so it does not shut down????
service class
public class MessengerService extends Service {
/** Command to the service to display a message */
static final int MSG_SAY_HELLO = 1;
static final int MSG_BOT_GET = 2;
static final int MSG_BOT_SET = 3;
static final int MSG_BOT_STOP = 4;
static final int MSG_BOT_PAUSE = 5;
static final int MSG_GET_ORDERS = 6;
static final int MSG_GET_POINT = 7;
static final int MSG_BOT_GET_RES = 2;
static final int PRICE_STATIC =1;
static final int PRICE_PERCENTAGE =2;
static final int PRICE_ALL = 3;
static final int VOL_STATIC = 1;
static final int VOL_PERCENTAGE = 2;
static final int VOL_ALL = 3;
int counter;
boolean isStop=false; // put bot in pause ste on next 1 min update
boolean isUYpdateNextMinute=false;
/**
This is called by a client to exicute code in this service
*/
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_BOT_GET:
Message resp = Message.obtain(null, MSG_BOT_GET_RES);
Bundle bResp = new Bundle();
bResp.putString("respData", Integer.toString(counter ));
resp.setData(bResp);
try {
msg.replyTo.send(resp);
} catch (Exception e)
{
}
Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
}
final Messenger mMessenger = new Messenger(new IncomingHandler());
/**
* When binding to the service, we return an interface to our messenger
* for sending messages to the service.
*/
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
return mMessenger.getBinder();
}
//////////////////////////////////////////////////////////////////////////////
// emplanent callbacks
MessengerService parent;
#Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
parent=this;
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
// sgart 1 minute update thread
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
///////////////////////////////////////////////////////////////
// thread code that runbs counter
class ThreadDemo extends Thread {
private String threadName;
ThreadDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
try {
do {
counter++;
Thread.sleep(1000 *60 );
counter++;
} while (true);
} catch(Exception e)
{
Toast.makeText(parent, "thread stopped", Toast.LENGTH_LONG).show();
}
} // end inner thread class
} // end class
}
/////////////////////////////////////////////////////////////////////
activity class
public class ActivityBoundMessenger extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bound_messenger);
}
/** Messenger for communicating with the service. */
Messenger mService = null;
/** Flag indicating whether we have called bind on the service. */
boolean mBound;
/**
* Class for interacting with the main interface of the service.
*/
/////////////////////////////////////////////////////////////////////////////////////////
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mService = new Messenger(service);
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
mBound = false;
}
};
////////////////////////////////////////////////////////////////////////////////
public void sayHello(View v) {
if (!mBound) return;
// Create and send a message to the service, using a supported 'what' value
Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void butSet(View v) {
if (!mBound) return;
// Create and send a message to the service, using a supported 'what' value
Message msg = Message.obtain(null, MessengerService.MSG_BOT_SET, 0, 0);
Bundle b = new Bundle();
b.putString("data", "json object");
msg.setData(b);
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
public void butGet(View v) {
if (!mBound) return;
// Create and send a message to the service, using a supported 'what' value
Message msg = Message
.obtain(null, MessengerService.MSG_BOT_GET);
msg.replyTo = new Messenger(new ResponseHandler());
// We pass the value
try {
mService.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
////////////////////////////////////////////////////////////////////////////////////////
// these metheds get called whenb this acty starts and endsa
#Override
protected void onStart() {
super.onStart();
// Bind to the service
////////////////////////////////////////////
Intent ser = new Intent(this, MessengerService.class);
startService(ser);
bindService(ser, mConnection,
Context.BIND_AUTO_CREATE);
///////////////////////////////////////////
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
// This class handles the Service response
int ted=0;
String nextUpdate=null;
class ResponseHandler extends Handler {
#Override
public void handleMessage(Message msg) {
int respCode = msg.what;
switch (respCode) {
case MessengerService.MSG_BOT_GET_RES:
String nextUpdate= msg.getData().getString("respData");
ted++;
}
}
}
}
From Android Documentation:
When the last client unbinds from the service, the system destroys the service, unless the service was also started by startService().
So, all you have to do is call this in your onCreate() method in the Service:
startService(new Intent(this, MessengerService.class))
Of course make sure to call stopSelf() when you are done with the service.

Rapid IPC with Messengers or AIDL

I'm attempting to create a program in Android which communicates rapidly with a remote service (~40,000/sec), however all Android IPC seems to fall short of being able to accomplish this task. My first attempt involved a standard Messenger system which was unable to do more then ~2,000/second and equally bad was that it seemed punctuated with intermittent lag.
MainActivity (Test with Messengers)
public class MainActivity extends Activity implements ServiceConnection{
Messenger mServiceMessenger;
Messenger mClientMessenger = new Messenger(new ClientHandler());
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this,TestService.class);
bindService(intent,this, Context.BIND_AUTO_CREATE);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mServiceMessenger = new Messenger(service);
Message m = Message.obtain();
m.replyTo = mClientMessenger;
try {
mServiceMessenger.send(m);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {}
public class ClientHandler extends Handler {
#Override
public void handleMessage(Message msg) {
Log.d("Spam","Message Received");
}
}
}
RemoteService (Test with Messengers)
public class TestService extends Service {
private Messenger mServiceMessenger = new Messenger(new ServiceHandler());
private Messenger mClientMessenger;
private Random r = new Random();
public TestService() {
super();
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return mServiceMessenger.getBinder();
}
public void initSpam(){
for(int i=0;i<10;i++) {
TimerTask task = new TimerTask() {
#Override
public void run() {
Bundle b = new Bundle();
b.putInt("INT",r.nextInt());
b.putLong("LONG",r.nextLong());
b.putBoolean("BOOL",r.nextBoolean());
b.putFloat("FLOAT",r.nextFloat());
b.putDouble("DOUBLE",r.nextDouble());
b.putString("STRING",String.valueOf(r.nextInt()));
Message msg = Message.obtain();
msg.setData(b);
try {
mClientMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task,1,1);
}
}
public class ServiceHandler extends Handler {
#Override
public void handleMessage(Message msg) {
mClientMessenger = msg.replyTo;
initBarrage();
}
}
}
The second attempt was done with AIDL. Although this also implements Binders for IPC, I assumed had significantly less overhead. However, AIDL proved to not be significantly more efficient then Messengers and it also did not solved the issue with stuttering.
MainActivity (Test with AIDL)
public class MainActivity extends Activity implements ServiceConnection{
IRemoteService mService;
TextView countTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this,TestService.class);
bindService(intent,this, Context.BIND_AUTO_CREATE);
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IRemoteService.Stub.asInterface(service);
try {
mService.registerCallback(mClientBinder);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {}
public final IServiceAidlCallback.Stub mClientBinder = new IServiceAidlCallback.Stub(){
public void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString){
Log.d("Spam","Callback Received");
}
};
}
RemoteService (Test with AIDL)
public class TestService extends Service {
private Random r = new Random();
private IServiceAidlCallback mClientCallback;
public TestService() {
super();
}
#Override
public void onRebind(Intent intent) {
super.onRebind(intent);
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public final IRemoteService.Stub mBinder = new IRemoteService.Stub(){
public void registerCallback(IBinder callback){
mClientCallback = IServiceAidlCallback.Stub.asInterface(callback);
initSpam();
}
};
public void initSpam(){
for(int i=0;i<10;i++) {
TimerTask task = new TimerTask() {
#Override
public void run() {
try {
mClientCallback.basicTypes(
r.nextInt(),
r.nextLong(),
r.nextBoolean(),
r.nextFloat(),
r.nextDouble(),
String.valueOf(r.nextInt()));
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task,1,1);
}
}
}
Am I doing something wrong in either of these cases which would prevent me from getting above ~5,000/second? or is there another system for Android IPC that I was not aware of?
do something like that:
MainActivity
// use it for writing: stream.write(byte[])
// (make sure to write as biggest data chunks as possible)
// or wrap it around some other streams like DataOutputStream
private OutputStream stream;
// ServiceConnection implementation
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
try {
ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();
stream = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]);
Parcel data = Parcel.obtain();
FileDescriptor readFileDescriptor = pipe[0].getFileDescriptor();
data.writeFileDescriptor(readFileDescriptor);
service.transact(IBinder.FIRST_CALL_TRANSACTION, data, null, 0);
} catch (Exception e) {
e.printStackTrace();
}
Log.d(TAG, "onServiceConnected " + stream);
}
RemoteService
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind ");
return binder;
}
IBinder binder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
ParcelFileDescriptor pfd = data.readFileDescriptor();
final InputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(pfd);
// do something with a 'stream', start a new Thread for example and read data in a loop
...
...
return true;
}
};

Android doesn't kill bound service

I am creating bound service for socket connection.Which means it is creating a long polling connection and listens my server.If user closes the app in task manager my service is killing i have no problem with this.But when user presses the back button I am calling activity.finish() method for close app.But with this method my service doesn't kill,it is still connected to socket server.
Is this normal ? And Could be this drain the battery ?
My service:
public class SocketService extends Service {
//you need constants to tell servise and activity what you are sending a message for
public static final int REGISTER_CHAT_ACTIVITY = 1;
public static final int MESSAGE_RECEIVED = 2;
final Messenger mMessenger = new Messenger(new IncomingHandler());
Messenger chat;
private Socket socket;
#Override
public void onCreate() {
try {
socket = IO.socket("ip");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("connected", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("message", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
chat.send(android.os.Message.obtain(null, MESSAGE_RECEIVED, args[0]));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//and add all the other on listeners here
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (socket != null) {
socket.disconnect();
socket.connect();
} else {
try {
socket = IO.socket("ip");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(android.os.Message msg) {
switch(msg.what){
case REGISTER_CHAT_ACTIVITY:
chat = msg.replyTo;
break;
}
}
}
public class LocalBinder extends Binder {
SocketService getService() {
return SocketService.this;
}
}
}
I had something similar a while ago i solved the issue by using shared preferences.(Note: I dont think it's the best answer but it solved my problem)
I saved in preferences a boolean to register when i dont need the service anymore but lost reference of it.
public class YourService extends Service {
private YourService serv;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
serv = this;
Then Somehwere on your code that the service does frequently.
if(!sharedPref.getBoolean("TurnOffService", false)){
serv.stopSelf();
}
Hope it helps.

AsynchTask should not stop when I terminates Application

I am making AsynkTask within Service like this
public class MyService extends Service {
private final IBinder mBinder = new LocalBinder();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("log_tag", "Service started");
ReceiveAsyncTask receiveATask = new ReceiveAsyncTask();
receiveATask.execute();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.v("log_tag", "onBind");
return mBinder;
}
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
class ReceiveAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
taskDummy();
return null;
}
#Override
protected void onPreExecute() {
Log.v("log_tag", "onPreExecute");
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
Log.v("log_tag", "onPostExecute");
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
Log.v("log_tag", "onPostExecute");
super.onCancelled();
}
}
private void taskDummy() {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("log_tag", "taskDummy");
}
}
/** method for clients */
public int getRandomNumber() {
Log.v("log_tag", "inner Method called");
return 100;
}
}
when I am running the application it starting to print "taskDummy" every two second as expected, when I close application by prssing Back buttin still log printing continue as expected, but when I removed application from recent apps stack it stopped printing this should not happen I want my asynch task continue in this situation. even I can see my service is running from setting. please advise me.
You need to explicitly call of asyncTaskObject.cancel(true); in onDestroy of your Activity(Or your event whenever you want.)
And then rewrite your while loop logic , something like that:
// Create this variable is Your Asyantask class.
private boolean isRunning = true;
#Override
protected void onCancelled() {
isRunning = false;
}
#Override
protected String doInBackground(Void... params) {
while (isRunning ) {
// Your processing
}
return null;
}
It's a known bug: swiping the service out from recent apps destroys it.
Try following solution.

send heartbeat gcm?

I develop android app use GCM, i want to send heartbeat for every 5 minutes at once, i create it when service is run,these are my codes,
public class sendHeartbeat extends Service{
private Handler customHandler = new Handler();
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate");
}
#Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, "onStart");
customHandler.postDelayed(updateTimerThread, 0);
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
}
private Runnable updateTimerThread = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new syncGetHeartbeat().execute();
Log.d("send hearbeat","send hearrrrrrrbeat");
customHandler.postDelayed(this, 260000);
}
};
class syncGetHeartbeat extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... unsued) {
try {
String varId="naengoland";
String url = "http://mydomain.com/gcmserver/getHeartbeat.php?id="+varId;
getRequestJSON(url);
return null;
} catch (Exception e) {
Log.e(e.getClass().getName(), "service get hertbeat "+ e.toString());
return null;
}
}
#Override
protected void onProgressUpdate(Void... unsued) {
}
#Override
protected void onPostExecute(String sResponse) {
}
}
public String getRequestJSON(String Url){
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
client.execute(request);
}catch(Exception ex){
}
return null;
}
}
I successfully send the heartbeat for every 5 minutes, but the problem is my app running slowly and consume battery a lot, is there any way to send heartbeat beside doing my way?
i mean,the better method than my method.
Please help.
Using TimerTask provides better performance than using Thread (ref).. However TimerTask isn't good in handling multiple threads at the same time which isn't a concern in your case because you are doing one task repeatedly.
here is the code for Timer:
first initialize a Timer:
private Timer timer;
in onCreate:
timer = new Timer();
then within onStart:
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
new syncGetHeartbeat().execute();
Log.d("send hearbeat","send hearrrrrrrbeat");
}
}, 0, 300000); //means start at 0 second and each 5 mins (300000 ms) run the task
I'm not sure if there is another solution that has better performance however this is absolutely better than running thread in a fixed rate.

Categories

Resources