user3051460 user3051460 - 1 month ago 8
Android Question

Do you think Thead.sleep() is a good approach in Service?

I have a service as

MyService
. In my service, I have a global variable:
value
which is controled by a function
control_Value()
. The function used to control the value of varialbe
value
as follows rules:


The time when calling the function is called initial time. At intial time, the value is set as
One
. After 3 seconds from initial time, the value is set to
Zero
. The value will maintain
Zero
until the function is called again.


Based on the rule above, I wrote the
control_Value()
as follows:

public void control_Value()(){
value="One";
try{
Thread.sleep(3000);
value="Zero";
}
catch{}
}


Do you think Thead.sleep(3000) is a good approach? If not, please give me a better solution. Note that, the above function worked well.

This is my service

public class MyService extends Service {
String value=null;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful

return Service.START_NOT_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
@Subscribe
public void onSMSContentReceived(OnSMSReceiverEvent event) {
control_Value();
}
}


Update: The
onSMSContentReceived
is called automatically when a SMS come to phone.

This is solution using countdown timer from suggestion of TGMCians

//Global variable
private CountDownTimer mCountDownTimer;
//
@Override
protected void onDestroy() {
if(mCountDownTimer!=null){
mCountDownTimer.cancel();
}
super.onDestroy();
}
public void control_Value()(){

mCountDownTimer = new CountDownTimer(3000,1000) {
@Override
public void onTick(long millisUntilFinished) {
value="One";
}
@Override
public void onFinish() {
// Your stuff
value="Zero";
}
};
mCountDownTimer.start();
}

Answer

Do you think Thead.sleep(3000) is a good approach?

Never. Service run on application main thread without UI. Application will prompt ANR message in case you hold application main thread for certain seconds.

What to do

If you want to perform operation after certain seconds, then you can use CountDownTimer in your service which has methods onTick & onFinish where onTick hits on regular interval and onFinish hits when time is up.