2013-03-12 2 views
3

비동기 작업을 실행하여 특정 정확도로 좌표를 가져오고 좌표를 얻으면 다른 활동을 시작합니다.설정된 시간 초과에 대해 비동기 작업을 실행하는 방법?

이제 설정 한 정확도로 좌표를 얻지 못하면 비동기 작업이 자체적으로 삭제되어야하며 (위치 업데이트를 제거하는 등) Lattitude/Longitude의 기본값은 다음과 같습니다. 통과했다.

new GetGPShotfix().execute().get(1, TimeUnit.MINUTES); 나는이 비동기에 대한 제한 시간을 분으로 설정 한 다음이 비동기 실행 호출 아래의 다음 줄/작업으로 진행하려고했습니다.

그러나 제 경우에는 Async가 설정 한 시간 초과를 기다리지 않고 다음 줄로 건너 뜁니다.

내가 원하는 방식으로 실행하려면 어떻게해야합니까? 다음 (gpshotfix()에 비동기) 내 코드입니다 : 나는 또한 스레드의 join()하지만 분명히 결과는 동일 :(

업데이트 있었다 사용하여 시도

어떤 도움이 감지 할 수있다
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 {} 
    } 
} 

..

+0

코드도 게시하십시오. – basiljames

+1

'GetGPShotfix' 클래스는 무엇입니까? – Javier

+0

AsyncTask 계산이 2 SEC 내에서 완료되었다고 가정하면 1 분을 기다리지 않습니다. –

답변

6

execute.get (1, TimeUnit.MINUTES)을 사용하면 비동기 작업이 synchronus로 변환됩니다. 비동기 작업을 사용하면 아무 소용이 없습니다. asynctask를 시작할 때 별도의 스레드를 시작하여 시간을 감시하고 필요한 작업을 수행 할 수 있습니다 그 후에 당신은 ru를 구현하는 클래스를 만들 수 있습니다. nnable을 호출하고 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

안녕하세요, 내 코드와 관련하여 pls 정교 할 수 있습니까? 나는 당신의 코드를 얻지 않습니까? : | – beerBear

+0

Null Pointer Ex를 얻고 있습니다. (if (mAT.getStatus() == Status.RUNNING || mAT.getStatus() == Status.PENDING) {'[Here] (http://pastebin.com/JLzU6SE7)에서 설정 시간 초과 (10 초) (붙여 넣기 링크)는 내가 꼬마 도깨비 인 방법이다. 이. btw는 나를 통해 나를 도와 주셔서 고마워요. : D – beerBear

+0

좋아, 내 실수는 어디에 있었는지 : D (생성자가 제대로 초기화되지 않았습니다.)하지만 이제는 응용 프로그램이 gps 잠금을 얻지 못하고 시간 초과가 무시됩니다. – beerBear

관련 문제