在固定的时间间隔后停止服务和计时器,android?

时间:2013-08-07 05:03:07

标签: android service timer

在我的应用程序中,我有一项服务实现计时器任务,通过该任务我每10秒钟就会获得一次用户的位置。

我坚持的是我想在1或2分钟之后停止这项服务以及计时器。

我无法为它提供逻辑。 请帮帮我。

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();

     }
   }
}

3 个答案:

答案 0 :(得分:3)

@Wishy在某个时间停止服务和计时器任务,你需要做一个其他计时器任务,执行一次,执行时间将是你指定的任何时间。在run方法中你需要编写mTimer.purge(); mTimer.cancel()和stopService(newIntent(class.this,yourservice.class));

答案 1 :(得分:0)

更简单的解决方案是使计时器公共静态

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

另一项活动:

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

答案 2 :(得分:0)

  1. 覆盖服务类中的onDestroy()方法,如下所示:

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

  2. 在那里调用stopService()停止服务,如下所示:

  3. stopService(serviceIntent);

    就是这样。