我想运行我的异步任务,它以一定的准确度获取共同的声音,并在它获得坐标时激发不同的活动.
现在我想设置一个时间,这样如果它没有得到设定精度的坐标,那么Async任务应该自行销毁(删除位置更新等)并传递Lattitude / Longitude的默认值.
我试过用这个:
new GetGPShotfix().execute().get(1,TimeUnit.MINUTES);以便为此异步设置一个超时的超时,然后继续执行此异步执行调用下面的下一行/任务.
但在我的情况下,它跳过下一行而不等待Async设置的超时.
我怎样才能让它按照我想要的方式执行?我也尝试使用线程的join()但显然结果是相同的:(
更新:
这是我的代码(对于gpshotfix()Async):
private class GetGPShotfix extends AsyncTask<VoID, VoID, VoID> { // ProgressDialog progressDialogGPS; @OverrIDe protected voID onPreExecute() { super.onPreExecute(); Log.i("GPSfixer", "Ready to get GPS Hotfix"); } @OverrIDe protected VoID doInBackground(VoID... params) { try { LocationRetrIEver myLoc = new LocationRetrIEver(); // myLoc.getUserLoc(); //if (gotLoc == 0 && (firstLoc.getAccuracy() > 10)) { if (gotLoc == 0) { myLoc.getUserLoc(); } } catch (Exception e) { Log.i("GPSfixer", "GPS Hotfix Failed!", e); } finally { Log.i("GPSfixer", "Get GPS Hotfix Completed..."); } return null; } @OverrIDe protected voID onCancelled() { Log.i("GPSfixer", "Get GPS Hotfix Cancelled"); } @OverrIDe protected voID onPostExecute(VoID result) { super.onPostExecute(result); Log.i("GPSfixer", "GPS Hotfix cycle completed"); System.out.println("Lon :" + myCurrentLon + "Lon2: " + finalLonNow); System.out.println("Lat :" + myCurrentLat + "Lat2: " + finalLatNow); //pDialog2.dismiss(); // progressDialogGPS.dismiss(); }}public class LocationRetrIEver { final LocationManager locationManager = (LocationManager) StoreSelection.this.getSystemService(Context.LOCATION_SERVICE); final LocationListener locationListener = new LocationListener() { public voID onProvIDerDisabled(String provIDer) { // Todo auto-generated method stub Toast.makeText(getApplicationContext(), provIDer + " is Disabled!", Toast.LENGTH_SHORT).show(); Toast.makeText(getApplicationContext(), "Please standby..enabling " + provIDer, Toast.LENGTH_SHORT).show(); // explicitly enable GPS Intent enableGPS = new Intent("androID.location.GPS_ENABLED_CHANGE"); enableGPS.putExtra("enabled", true); sendbroadcast(enableGPS); // explictly disable GPS /* * Intent intent = new * Intent("androID.location.GPS_ENABLED_CHANGE"); * intent.putExtra("enabled", false); sendbroadcast(intent); */ } public voID onProvIDerEnabled(String provIDer) { // Todo auto-generated method stub Toast.makeText(getApplicationContext(), provIDer + " is enabled..", Toast.LENGTH_SHORT).show(); } public voID onStatusChanged(String provIDer, int status, Bundle extras) { // Todo auto-generated method stub /* * System.out.println("val of status: " + status + " provIDer: " * + provIDer); */ if (status == 1) { Toast.makeText(getApplicationContext(), provIDer + " is enabled & available..", Toast.LENGTH_SHORT).show(); System.out.println(provIDer + " is NOT available!"); } else { System.out.println(provIDer + " is NOT available!"); } /* progressDialogGPS.dismiss(); */ } public voID onLocationChanged(Location location) { // Todo auto-generated method stub // ORIG CODE --BELOW-- // moved lat/lon vars to top ^ myCurrentLon = location.getLongitude(); myCurrentLat = location.getLatitude(); firstLoc = location; myCurrentLon = Double.parseDouble(new DecimalFormat("##.#########") .format(myCurrentLon)); myCurrentLat = Double.parseDouble(new DecimalFormat("##.#########") .format(myCurrentLat)); /*Toast.makeText(getApplicationContext(), myCurrentLat + " " + myCurrentLon, Toast.LENGTH_SHORT) .show();*/ System.out.println(myCurrentLat + " " + myCurrentLon); float acc=location.getAccuracy(); /*Toast.makeText(getApplicationContext(), "Acc.: " + acc,Toast.LENGTH_SHORT).show();*/ // -- // get best out of 2 locs. --BEGINS-- /* * makeUSEOfNewLocation(location); * * if(currentBestLocation == null){ currentBestLocation = * location; } */ if (myCurrentLon != null && myCurrentLat != null && (firstLoc.getAccuracy() <= 10)) { // added // chk // for // online.. gotLoc = 1; System.out.println("OK GOTLOC == 1 !"); System.out.println("Got your Current Location..disabling GPS to save Battery Power.."); Toast.makeText(getApplicationContext(), "Got your Current Location..disabling GPS to save Battery Power..", Toast.LENGTH_SHORT).show(); // removing updates // locationManager.removeUpdates(locationListener); // explicitly turning off GPS Intent intent = new Intent("androID.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", false); sendbroadcast(intent); System.out.println("GPS Disabled!"); finalLatNow = myCurrentLat; finalLonNow = myCurrentLon; // // if(gotLoc == 0){ if (myCurrentLon != null && myCurrentLat != null && (firstLoc.getAccuracy() <= 10)) { // locationManager.removeUpdates(locationListener); gotLoc = 1; Intent i = new Intent(StoreSelection.this, LastVisitDetails.class); i.putExtra("currUsrLon", myCurrentLon); // 2nd i.putExtra("currUsrLat", myCurrentLat); // 1st i.putExtra("storeID", selStoreID); i.putExtra("selStorename", selStorename); i.putExtra("imei", uuID); i.putExtra("date", userDate); runOnUiThread(new Runnable() { public voID run() { try { // stuff here pDialog2.dismiss(); } catch (Exception e) { e.printstacktrace(); } } }); System.out.println("--Removing Loc. Updates--"); remUpdates(); syncTIMESTAMP = System.currentTimeMillis(); Date dateobj = new Date(syncTIMESTAMP); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); fullfilename1 = df.format(dateobj); dbengine.open(); dbengine.UpdateStoreStartVisit(selStoreID, fullfilename1); dbengine.close(); startActivity(i); finish(); } else { if (myCurrentLon == null && myCurrentLat == null) { // alert + GPS not locking on..do something() } else { } /*if (!isOnline()) { // alert + not online...do something() showNoConnAlert(); } else { }*/ } // /* * } else{} */ } else { System.out.println("INSIDE ELSE -- GOTLOC"); } } }; // locationManager.requestLocationUpdates(locationManager.getBestProvIDer(new // Criteria(), true), 2000, 4, locationListener); // enable gps everytime we request location update /* * Intent enableGPS = new Intent("androID.location.GPS_ENABLED_CHANGE"); * enableGPS.putExtra("enabled", true); sendbroadcast(enableGPS); */ // ** ORIG Grequest location updates from GPS string /* * locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, * ONE_MIN, 4, locationListener); */ // ** Now remove updating of co-ordinates // locationManager.removeUpdates(locationListener); /*public Location getBestLoc(){ if(firstLoc.getAccuracy() <= newLoc.getAccuracy() && newLoc.getAccuracy() <= 10) { return firstLoc; } else if(newLoc.getAccuracy() <= firstLoc.getAccuracy() && newLoc.getAccuracy() <= 10){ return newLoc; } else { return newLoc; } }*/ voID getUserLoc() { if (gotLoc == 1 && (firstLoc.getAccuracy() <= 10)) { locationManager.removeUpdates(locationListener); } else { } final Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setHorizontalAccuracy(Criteria.ACCURACY_FINE); // criteria.setVerticalAccuracy(Criteria.NO_REQUIREMENT); criteria.setAltituderequired(false); // criteria.setbearingAccuracy(Criteria.NO_REQUIREMENT); criteria.setbearingrequired(false); criteria.setCostAllowed(true); criteria.setPowerRequirement(Criteria.POWER_HIGH); runOnUiThread(new Runnable() { public voID run() { try { // stuff here /* * progressDialogGPS = ProgressDialog.show(_activity, * null, null); * progressDialogGPS.setContentVIEw(R.layout.loader); * progressDialogGPS * .getwindow().setType(WindowManager.LayoutParams * .TYPE_KEyguard_DIALOG); */ /*locationManager .requestLocationUpdates(locationManager .getBestProvIDer(criteria, true), TEN_SECS, 4, locationListener);*/ locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0l, 0.0f, locationListener); // remove updates # if (gotLoc == 1 && (firstLoc.getAccuracy() <= 10)) { locationManager.removeUpdates(locationListener); } else { } } catch (Exception e) { e.printstacktrace(); } } }); /* * try { Thread.currentThread().sleep(2000); } catch * (InterruptedException e) { // Todo auto-generated catch block * e.printstacktrace(); } */ } voID remUpdates() { //if(firstLoc.getAccuracy() <= 10){ locationManager.removeUpdates(locationListener); //} //else {} }}
任何帮助都很明显..
解决方法:
使用execute.get(1,TimeUnit.MINUTES)时,它会将异步任务转换为synchronus.在这种情况下,使用异步任务是没有用的.您可以在启动asynctask时启动单独的线程以保持监视时间并在此之后执行所需的 *** 作.您可以创建一个实现runnable的类,并将asyctask作为构造函数参数传递并在其中取消它.
class checkAyscTask implements Runnable { AsyncTask<VoID, VoID, Boolean> mAT; Context context; public checkAyscTask(AsyncTask<VoID, VoID, Boolean> at) { mAT = at; } @OverrIDe public voID run() { mHandler.postDelayed(runnable, 60000); // After 60sec the task in run() of runnable will be done } Handler mHandler = new Handler(); Runnable runnable = new Runnable() { @OverrIDe public voID run() { if (mAT.getStatus() == Status.RUNNING || mAT.getStatus() == Status.PENDING) { mAT.cancel(true); //Cancel Async task or do the operation you want after 1 minute } } };}task_GetGPS = new GetGPShotfix(); task_GetGPS.execute();checkAyscTask chk = new checkAyscTask(task_GetGPS);// Thread keePing 1 minute time watch(new Thread(chk)).start();
总结 以上是内存溢出为你收集整理的如何为设置超时运行异步任务?全部内容,希望文章能够帮你解决如何为设置超时运行异步任务?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)