I have a situation in an Android app where I want to start a network activity (sending out some data) which should run every second. I achieve this as follows:
In th
Perhaps involve the activity's life-cycle methods to achieve this:
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler.post(sendData);
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(sendData);
}
private final Runnable sendData = new Runnable(){
public void run(){
try {
//prepare and send the data here..
handler.postDelayed(this, 1000);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
In this approach, if you press back-key on your activity or call finish();
, it will also stop the postDelayed callings.
Why don't you create service and put logic in onCreate()
. In this case even if you press back button service will keep on executing. and once you enter into application it will not call
onCreate()
again. Rather it will call onStart()
Handler h = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==0){
// do stuff
h.removeMessages(0); // clear the handler for those messages with what = 0
h.sendEmptyMessageDelayed(0, 2000);
}
}
};
h.sendEmptyMessage(0);
You can simplify the code like this.
In Java:
new Handler().postDelayed (() -> {
//your code here
}, 1000);
In Kotlin:
Handler().postDelayed({
//your code here
}, 1000)
I think you could experiment with different activity flags, as it sounds like multiple instances.
"singleTop" "singleTask" "singleInstance"
Are the ones I would try, they can be defined inside the manifest.
http://developer.android.com/guide/topics/manifest/activity-element.html
You should set andrid:allowRetainTaskState="true" to Launch Activity in Manifest.xml. If this Activty is not Launch Activity. you should set android:launchMode="singleTask" at this activity