gpt4 book ai didi

java - 计时器未在预定时间被调用

转载 作者:行者123 更新时间:2023-12-02 02:43:48 24 4
gpt4 key购买 nike

我想每 10 分钟跟踪一次位置,并通过 TraceDelivery 异步任务将其发送到服务器。为此,我尝试使用服务和计时器每 10 分钟获取一次位置。

但是,当我从另一个 Activity 调用该服务时,它只能工作一次,即一次 TraceDelivery api 被调用,但不会再次调用。为了测试,我只给出了第二次延迟,但它仍然没有被再次调用。

此外,如果我检查 mLatLang 是否为 null,然后调用 TraceDelivery,它至少不会被调用一次。但如果 location 为 null,它会因 mLatLang 上的空指针而崩溃。

服务代码:

public class LocationTrackerService extends IntentService implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener{

private Handler handler;
private Timer timer;
private TimerTask timerTask;
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
private LatLng mLatLang;
LocationManager mLocationManager = null;
boolean gps_enabled = false;
boolean network_enabled = false;


LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.NETWORK_PROVIDER),
new LocationListener(LocationManager.GPS_PROVIDER)

};

/**
* A constructor is required, and must call the super IntentService(String)
* constructor with a name for the worker thread.
*/
public LocationTrackerService() {
super("HelloIntentService");
}

/**
* The IntentService calls this method from the default worker thread with
* the intent that started the service. When this method returns, IntentService
* stops the service, as appropriate.
*/
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(1000);

buildGoogleApiClient();
mGoogleApiClient.connect();

handler = new Handler();

initializeLocationManager();
requestLocation();


startTimer(intent.getStringExtra("dl_id"), intent.getStringExtra("pt_id"), intent.getStringExtra("ur_id"),intent.getStringExtra("address"),
intent.getStringExtra("api_key"));


} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
public void startTimer(String dlId,String ptId,String urId,String add,String key) {
//set a new Timer
timer = new Timer();

//initialize the TimerTask's job
initializeTimerTask(dlId, ptId, urId,key);

//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
timer.schedule(timerTask, 1000, 1000);//
}

public void initializeTimerTask(final String dlId, final String ptId, final String urId, final String key) {

timerTask = new TimerTask() {
public void run() {

//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {

TraceDeliveryAsyncTask traceDeliveryAsyncTask = new TraceDeliveryAsyncTask(LocationTrackerService.this);
traceDeliveryAsyncTask.execute(dlId, ptId, urId, String.valueOf(mLatLang.latitude),
String.valueOf(mLatLang.longitude),"", key);

Log.e("timer","success");


}
});
}
};
}

public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}

protected synchronized void buildGoogleApiClient() {

mGoogleApiClient = new GoogleApiClient.Builder(LocationTrackerService.this)
.addConnectionCallbacks(LocationTrackerService.this)
.addOnConnectionFailedListener(LocationTrackerService.this)
.addApi(LocationServices.API)
.build();
}

@Override
public void onConnected(Bundle bundle) {
// Toast.makeText(getActivity(),"onConnected",Toast.LENGTH_SHORT).show();

}

@Override
public void onConnectionSuspended(int i) {
// Toast.makeText(getActivity(),"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Toast.makeText(getActivity(),"onConnectionFailed",Toast.LENGTH_SHORT).show();
}

private void initializeLocationManager() {
// Log.e(Application.TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}

try {
gps_enabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}

try {
network_enabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}

if (!gps_enabled && !network_enabled) {
// notify user
if(!CommonUtils.isGPSEnabled(getApplicationContext()))
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}

}

public class LocationListener implements android.location.LocationListener {

public LocationListener() {
}

public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}

@Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);

//get current location

if(mLastLocation != null && !mLastLocation.equals("")) {
mLastLocation.set(location);
mLatLang = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
}
else {

}

}

@Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);

}

@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}

//request for location, first by network, then by gps

public void requestLocation() {

try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}

try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}

}

我怎样才能实现这个目标?请帮忙解决这个问题。谢谢..

最佳答案

IntentService 将在完成 OnHandleIntent 中的任务后立即停止,

因此,不要使用 IntentService,而是尝试使用 Service 来进行长时间运行的操作。

关于java - 计时器未在预定时间被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44982985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com