WISHY
WISHY

Reputation: 11999

Stop a service and timer after fixed interval of time, android?

In my app, I have a service implementing timer task through which i am getting user's location after every 10 seconds.

The thing I am stuck with is I would like to stop this service as well as timer after say 1 or 2 minutes.

I am not able to put behind the logic for it. Please help me out.

public class TimeService extends Service {
// constant
public static final long NOTIFY_INTERVAL = 20 * 1000; // 10 seconds

// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
int i=0;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    // cancel if already existed
    if(mTimer != null) {
        mTimer.cancel();
    } else {
        // recreate new
        mTimer = new Timer();
    }
    // schedule task
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}

class TimeDisplayTimerTask extends TimerTask {

    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {
             @Override
            public void run() {
                // display toast
                Toast.makeText(getApplicationContext(), getDateTime(),
                        Toast.LENGTH_SHORT).show();
                new LongOperation().execute("");
            }
         });
    }

    private String getDateTime() {
        // get date time in custom format
        SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
        return sdf.format(new Date());
    }
 }

private class LongOperation extends AsyncTask<String, Void, String> {
            @Override
    protected String doInBackground(String... params) {
        System.out.println("bgnotification Long operation doinbackground called----> "); 
        return "";
    }      

    @Override
    protected void onPostExecute(String result) {
        System.out.println("bgnotification Long operation post execute called----> ");
        if(i<3){ 
            GPSTracker mGPS = new GPSTracker(getApplicationContext());
         onLocationChanged(mGPS);i++;
         Toast.makeText(getApplicationContext(), "HEllo Post execute called",
    }
    @Override
    protected void onPreExecute() {
        System.out.println("bgnotification Long operation pre execute called----> ");
    }
    @Override
    protected void onProgressUpdate(Void... values) {
    }
}


public void onLocationChanged(GPSTracker track) {
    // Getting latitude
    double latitude = track.getLatitude();
    // Getting longitude
    double longitude = track.getLongitude();
     System.out.println( latitude);
     System.out.println(     longitude);
     Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try
     {
         List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
         Log.e("Addresses","-->"+addresses);              
     }
     catch (IOException e)
     {
         e.printStackTrace();

     }
   }
}

Upvotes: 1

Views: 1962

Answers (3)

Md. Rashadul Alam
Md. Rashadul Alam

Reputation: 13

  1. Override onDestroy() method in service class like thus:

    @Override public void onDestroy() { super.onDestroy(); if (mTimer != null) { mTimer.cancel(); } }

  2. Call stopService() there where you want to stop your service, like thus:

stopService(serviceIntent);

That's all.

Upvotes: 0

Mazlum Ozdogan
Mazlum Ozdogan

Reputation: 218

An easier solution is making timer public static.

public class TimeService extends Service {
//...
private Timer mTimer = null;
//...
}

another Activity:

//...
if(TimeService.mTimer!=null) TimeService.mTimer.cancel();
//...

Upvotes: 0

Nand
Nand

Reputation: 614

@Wishy to stop service and timer task at certain time you need to make an other timer task which going to execute one time and execution time duration will be whatever you specify. In run method u need to write mTimer.purge(); mTimer.cancel() and stopService(newIntent(class.this,yourservice.class));

Upvotes: 3

Related Questions