I need to implement some works after X seconds and I don't want make it related with UI thread. So I create Thread as below. Specifically, I wanna my doWork1() working every 10s. And imgUpload() do not disurb my thread
private int cntUpdate; //count time to update work1
private int cntUpload; //count time to upload to server
private int cntlosing; //count time losing gps
private void creatThread(){
Thread myThread = new Thread(){
@Override
public void run(){
try{
while (!isInterrupted()){
Thread.sleep(1000);//1s
cntUpdate ++;
if(cntUpdate >= 10){ //10s
doWork1(); //AsyncTask
cntUpdate = 0;
}
cntUpload ++;
if(cntUpload > 100){//100s
imgUpload(); //AsyncTask
cntUpload = 0;
}
if(isGpsLosing()){ //checking every sec
cntlosing ++;
if(cntlosing > 500){
doSomething();
cntlosing = 0;
}
}
}
}catch (InterruptedException e) {
Log.d(TAG, "Interruped : " + e);
}
}
};
myThread.start();
}
When start doWork1() worked every 10s. But when imgUpload() work then doWork1() stopped. But time count still exactly. After imgUpload() finished then doWork1() sending consecutive in 1-2s. Normal: doWork1() - 10s - doWork1() - 10s - dowork1()...10s... When imgUpload doWork1() - 10s - doWork1() - 10s - imgUpload() - time to waiting upload finish (example 30s) - after 30s - doWord1() - 1s - doWork1() -1s -doWork1() - 10s - doWork1() - 10s... come back to normal work
private void doWork1(){
AsyncWork1 asyncWork1 = new AsyncWork1();
asyncWork1.execute();
}
public class AsyncWork1 extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... voids) {
databaseWork(); // get data from table, some calculates...
return null;
}
}
private void imgUpload(){
UpLoadImg upload = new UpLoadImg();
upload.execute();
}
public class UpLoadImg extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... voids) {
sendImgtoServer(); //
return null;
}
}
I try use timer for doWork1() but nothing change in my result
private void useTimerWork1(){
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run(){
doWork1
}
}, 0, 10*1000); //every 10s
}
I am googling and read some topics about thread in SO but all make me confused. I don't know where i missed. I am change from C embed to android. So it is make me stupid and unintelligible Edit me if my explain too complicated