簡體   English   中英

在固定的時間間隔后停止服務和計時器,Android嗎?

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

在我的應用程序中,我有一項服務,該服務實現了計時器任務,通過該服務,我每隔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();

     }
   }
}

@希望在特定時間停止服務和計時器任務,您需要執行另一個計時器任務,該任務將一次執行,執行時間將由您指定。 在運行方法中,您需要編寫mTimer.purge();。 mTimer.cancel()和stopService(newIntent(class.this,yourservice.class));

一個更簡單的解決方案是使計時器變為公共靜態

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

另一個活動:

//...
if(TimeService.mTimer!=null) TimeService.mTimer.cancel();
//...
  1. 這樣重寫服務類中的onDestroy()方法:

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

  2. 在您要停止服務的位置調用stopService(),如下所示:

stopService(serviceIntent);

就這樣。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM