2017-04-26 15 views
7

tôi cần để có được vị trí (By fusedlocation API) của người dùng sau khi ActivityRecognition Phát hiện trạng sử dụng (trong đó kêu gọi mỗi 3 phút), như IN_VEHICLE, ON_FOOT, CHẠY, vvLocation Đang cập nhật trên cơ sở tình trạng thiết bị

Trên mỗi sự kiện tôi cần vị trí của người dùng sau khoảng thời gian thông thường Ví dụ:

nếu người dùng vẫn là setInterval(5*60*60*1000); và kiểm tra vị trí tiếp theo cập nhật không muộn hơn 5 giờ. Nhưng ActivityRecognation sẽ gọi mỗi 3 phút.

nếu người dùng đang chạy sau đó setInterval(2*60*1000); và kiểm tra cập nhật vị trí tiếp theo không trước/Sau 2 phút. Nhưng ActivityRecognation sẽ gọi mỗi 3 phút.

nếu người dùng đang chạy, sau đó gửi vị trí cứ 1 phút nếu người dùng lái xe sau đó gửi vị trí 15 phút một lần.

Tôi đã cố đặt sai boolean theo số onConnected thành sai và đúng ở cấp lớp. Nhưng nó luôn luôn trở thành sự thật bởi vì toàn bộ dịch vụ Intent được gọi sau 3 phút.

if (startLocationFirst){ 
requestLocatonSetting(5*60*60*1000,3*60*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); 
    LocationAPIclient.connect();// RequestLocation and GoogleAPIClient won't call until device comes from another ActivityRecognation State running,walking etc. And keep Updating location every 5 hours. 
       } 

Issue Tôi hiện có

  • ActivityRecognation Gets User State mỗi 3 phút nhưng nó không nên tham gia vào startLocationFirst boolean cho đến khi nó đến từ một quốc gia khác ActivityRecognation và tiếp tục cập nhật vị trí như thiết lập bên trong startLocationFirst

Đây là IntentService với FusedLocation

public class Activity_Recognized_Service extends IntentService implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks, LocationListener { 
    /** 
    * Creates an IntentService. Invoked by your subclass's constructor. 
    * 
    * @param name Used to name the worker thread, important only for debugging. 
    */ 
    public static final String TAG = "###RECOGNISED SRVCE###"; 
    Timer timer; 
    GoogleApiClient LocationAPIclient; 
    LocationRequest mLocationRequest; 
    Location mCurrentLocation; 
    boolean startLocationFirst=true; 


    public Activity_Recognized_Service() { 
     super("Activity_Recognized_Service"); 
    } 

    public Activity_Recognized_Service(String name) { 
     super(name); 
    } 

    @Override 
    protected void onHandleIntent(@Nullable Intent intent) { 
     Log.d(TAG, "On Handle Intent"); 
     if (ActivityRecognitionResult.hasResult(intent)) { 
      Log.d(TAG, "ActivityRecognition Has Result"); 
      ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); 
      handleDetectedActivities(result.getProbableActivities()); 
      Navigation_Drawer nav = new Navigation_Drawer(); 
      nav.UserMovementResult(result); 

     } 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     Log.d(TAG,"On Create Calling"); 
     if (LocationAPIclient == null) { 
      Log.d(TAG, "Location API is NULL Value Of This "); 
      LocationAPIclient = new GoogleApiClient.Builder(this) 
        .addApi(LocationServices.API) 
        .addConnectionCallbacks(this) 
        .addOnConnectionFailedListener(this) 
        .build(); 
     } 

    } 

    private void handleDetectedActivities(List<DetectedActivity> probableActivities) { 

     for (DetectedActivity activity : probableActivities) { 
      switch (activity.getType()) { 
       case DetectedActivity.IN_VEHICLE: 
        Log.d(TAG, "In Vehicle " + activity.getConfidence()); 
        if (activity.getConfidence() >= 75) { 
         //Send Notification To User 
         NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
         builder.setContentText("In Vehicle"); 
         builder.setSmallIcon(R.drawable.elaxer_x); 
         builder.setContentTitle("Elaxer"); 
         NotificationManagerCompat.from(this).notify(0, builder.build()); 
         requestLocatonSetting(10*60*1000,8*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
         //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST 
         LocationAPIclient.connect(); 
         if (startLocationFirst){ 
          Log.d(TAG,"Start Location Update For Car"); 
         } 
        } 
        break; 
       case DetectedActivity.ON_BICYCLE: 
        Log.d(TAG, "On Bicycle " + activity.getConfidence()); 
        if (activity.getConfidence() >= 75) { 
         //Send Notification To User 
         NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
         builder.setContentText("On Bicycle"); 
         builder.setSmallIcon(R.drawable.elaxer_x); 
         builder.setContentTitle("Elaxer"); 
         NotificationManagerCompat.from(this).notify(0, builder.build()); 
         requestLocatonSetting(7*60*1000,5*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
         //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST 
         LocationAPIclient.connect(); 
        } 
        break; 
       case DetectedActivity.ON_FOOT: 
        Log.d(TAG, "On Foot " + activity.getConfidence()); 
        if (activity.getConfidence() >= 75) { 
         //Send Notification To User 
         NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
         builder.setContentText("On Foot"); 
         builder.setSmallIcon(R.drawable.elaxer_x); 
         builder.setContentTitle("Elaxer"); 
         NotificationManagerCompat.from(this).notify(0, builder.build()); 
        } 
        break; 
       case DetectedActivity.RUNNING: 
        Log.d(TAG, "On Running " + activity.getConfidence()); 
        if (activity.getConfidence() >= 75) { 
         //Send Notification To User 
         NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
         builder.setContentText("Running"); 
         builder.setSmallIcon(R.drawable.elaxer_x); 
         builder.setContentTitle("Elaxer"); 
         NotificationManagerCompat.from(this).notify(0, builder.build()); 
         requestLocatonSetting(3*60*1000,2*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
         //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST 
         LocationAPIclient.connect(); 
        } 
        break; 
       case DetectedActivity.STILL: 
        Log.d(TAG, "On Still " + activity.getConfidence()); 
        if (activity.getConfidence() >= 75) { 
         //Send Notification To User 
         NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
         builder.setContentText("Still"); 
         builder.setSmallIcon(R.drawable.elaxer_x); 
         builder.setContentTitle("Elaxer"); 
         NotificationManagerCompat.from(this).notify(0, builder.build()); 

          requestLocatonSetting(5*60*60*1000,3*60*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
          // requestLocatonSetting(3*60*1000,2*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST 
          LocationAPIclient.connect(); 


        } 
        break; 
       case DetectedActivity.TILTING: 
        Log.d(TAG, "On Tilting " + activity.getConfidence()); 
        if (activity.getConfidence() >= 75) { 
         //Send Notification To User 
         NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
         builder.setContentText("Tilting"); 
         builder.setSmallIcon(R.drawable.elaxer_x); 
         builder.setContentTitle("Elaxer"); 
         NotificationManagerCompat.from(this).notify(0, builder.build()); 

         requestLocatonSetting(3*60*1000,2*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
         //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST 
         LocationAPIclient.connect(); 
        } 
        break; 
       case DetectedActivity.WALKING: 
        Log.d(TAG, "On Walking " + activity.getConfidence()); 
        if (activity.getConfidence() >= 75) { 
         //Send Notification To User 
         NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
         builder.setContentText("Let's Walk"); 
         builder.setSmallIcon(R.drawable.elaxer_x); 
         builder.setContentTitle("Elaxer"); 
         NotificationManagerCompat.from(this).notify(0, builder.build()); 
         requestLocatonSetting(3*60*1000,2*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
         LocationAPIclient.connect(); 

        } 
        break; 
       case DetectedActivity.UNKNOWN: 
        Log.d(TAG, "UnKnown " + activity.getConfidence()); 
        break; 
      } 
     } 
    } 

    public void setTimer(int Minutes) { 
     Log.d(TAG, "=================================================="); 
     Log.d(TAG, "Set Timeer Starts It will Run Every " + Minutes); 
     int MilliSeconds = 60000 * Minutes; 
     final Handler handler = new Handler(); 
     timer = new Timer(); 
     TimerTask doAsynchronousTask = new TimerTask() { 
      @Override 
      public void run() { 
       handler.post(new Runnable() { 
        public void run() { 
         try { 
          //CODE THAT YOU WANT TO EXECUTE AT GIVEN INTERVAL 


         } catch (Exception e) { 
          // TODO Auto-generated catch block 
         } 
        } 
       }); 
      } 
     }; 
     timer.schedule(doAsynchronousTask, 0, MilliSeconds); 
     Log.d(TAG, "=================================================="); 
    } 


    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     Log.d(TAG, "On Connected Running"); 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      return; 
     } 
     mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(LocationAPIclient); 
     if (mCurrentLocation!=null){ 
      Log.d(TAG,"Last Known Location Is not Null "); 
      new Location_sendeToServer_AsyncTask(this).execute(String.valueOf(mCurrentLocation.getLatitude()),String.valueOf(mCurrentLocation.getLongitude()),String.valueOf(mCurrentLocation.getAccuracy())); 
     } 
     else { 
      Log.d(TAG,"Last Known Location Is NULL Start Location Updates"); 
      LocationServices.FusedLocationApi.requestLocationUpdates(LocationAPIclient,mLocationRequest,this); 
     } 

    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

    } 

    @Override 
    public void onLocationChanged(Location location) { 
     Log.d(TAG,"On Location Changed Calling"); 
     mCurrentLocation=location; 
     new Location_sendeToServer_AsyncTask(this).execute(String.valueOf(mCurrentLocation.getLatitude()),String.valueOf(mCurrentLocation.getLongitude()),String.valueOf(mCurrentLocation.getAccuracy())); 
     Log.d(TAG,"Stopping Location Update"); 
     // LocationServices.FusedLocationApi.removeLocationUpdates(LocationAPIclient,this); 
    } 

    public void requestLocatonSetting(int Interval,int FastestInterval,int LocationAccuracy){ 
     mLocationRequest=new LocationRequest(); 
     mLocationRequest.setInterval(Interval); 
     mLocationRequest.setFastestInterval(FastestInterval); 
     mLocationRequest.setPriority(LocationAccuracy); 

    } 

} 
+0

Câu hỏi này không dành cho các nguồn chính thức. bất kỳ ai có thể trả lời – androidXP

Trả lời

1

Tôi thực thi mã này sau khi thêm vài dòng vào cùng mã như trên.

  • Trước tiên tôi tuyên bố int tĩnh ở cấp lớp trong IntentServiceDectectedActivity.getType() trở int. static int detectedActivity;
  • Sau đó, tại tôi kiểm tra xem cùng một trạng thái của nó như cuối cùng như thế này if (activity.getConfidence() >= 75 && activity.getType()!=detectedActivity)

Đó của it.thanks để @Pablo Baxter người đã cho tôi một số loại logic để apply.I thử nghiệm này trên IntentService nhưng tôi cần phải kiểm tra nó trên dịch vụ vì vậy tôi có thể cập nhật vị trí. Sẽ sớm cập nhật.

0

EDIT

Dưới đây là một ví dụ tốt hơn chỉ sử dụng các mã bạn đã cung cấp ở trên:

Sử dụng dịch vụ này khi đăng ký ActivityRecognitionApi của bạn:

public class LocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 

    public static final String TAG = "###RECOGNISED SRVCE###"; 

    private GoogleApiClient apiClient; 
    private PendingIntent pendingIntent; 
    private DetectedActivity lastActivity; 

    @Nullable 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     apiClient = new GoogleApiClient.Builder(this) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 

     apiClient.connect(); 
     pendingIntent = PendingIntent.getService(this, 1, new Intent(this, YourIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flag, int startId) { 
     Log.d(TAG, "onStartCommand"); 
     if (ActivityRecognitionResult.hasResult(intent)) { 
      Log.d(TAG, "ActivityRecognition Has Result"); 
      ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent); 
      handleDetectedActivity(result); 

      /* You should really use LocalBroadcastManager to send events out to an activity for UI updates */ 

//   Navigation_Drawer nav = new Navigation_Drawer(); 
//   nav.UserMovementResult(result); 
     } 
     return START_STICKY; 
    } 

    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     Log.d(TAG, "On Connected Running"); 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      return; 
     } 
     Location location = LocationServices.FusedLocationApi.getLastLocation(apiClient); 
     if (location!=null){ 
      Log.d(TAG,"Last Known Location Is not Null "); 
      Intent intent = new Intent(this, YourIntentService.class).putExtra("lastKnown", location); 
      startService(intent); 

      /* No more need for this! */ 
//   new Location_sendeToServer_AsyncTask(this).execute(String.valueOf(mCurrentLocation.getLatitude()),String.valueOf(mCurrentLocation.getLongitude()),String.valueOf(mCurrentLocation.getAccuracy())); 
     } 
     else { 
      Log.d(TAG,"Last Known Location Is NULL Start Location Updates"); 
      updateLocationSetting(5*60*60*1000,3*60*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); 
//   LocationServices.FusedLocationApi.requestLocationUpdates(apiClient,mLocationRequest,this); 
     } 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

    } 

    private void handleDetectedActivity(ActivityRecognitionResult result) { 
     DetectedActivity mostProbableActivity = result.getMostProbableActivity(); 
     switch (result.getMostProbableActivity().getType()) { 
      case DetectedActivity.IN_VEHICLE: 
//     Log.d(TAG, "In Vehicle " + activity.getConfidence()); 
       if (mostProbableActivity.getConfidence() >= 75 && mostProbableActivity != lastActivity) { 
        //Send Notification To User 
//      NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
//      builder.setContentText("In Vehicle"); 
//      builder.setSmallIcon(R.drawable.elaxer_x); 
//      builder.setContentTitle("Elaxer"); 
//      NotificationManagerCompat.from(this).notify(0, builder.build()); 
        //requestLocatonSetting(6*60*1000,6*60*1000,LocationRequest.PRIORITY_HIGH_ACCURACY); //TEST 
        if (apiClient.isConnected()) { 
         updateLocationSetting(10 * 60 * 1000, 8 * 60 * 1000, LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
         lastActivity = mostProbableActivity; 
        } 
       } 
       break; 
      case DetectedActivity.ON_BICYCLE: 
       Log.d(TAG, "On Bicycle " + mostProbableActivity.getConfidence()); 
       if (mostProbableActivity.getConfidence() >= 75 && mostProbableActivity != lastActivity) { 
        //Send Notification To User 
//     NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
//     builder.setContentText("On Bicycle"); 
//     builder.setSmallIcon(R.drawable.elaxer_x); 
//     builder.setContentTitle("Elaxer"); 
//     NotificationManagerCompat.from(this).notify(0, builder.build()); 
        if (apiClient.isConnected()) { 
         updateLocationSetting(7 * 60 * 1000, 5 * 60 * 1000, LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
         lastActivity = mostProbableActivity; 
        } 
       } 
       break; 

      case DetectedActivity.ON_FOOT: 
       Log.d(TAG, "On Foot " + mostProbableActivity.getConfidence()); 
       if (mostProbableActivity.getConfidence() >= 75) { 
        DetectedActivity nextHighest = result.getProbableActivities().get(1); 
        if (nextHighest.getType() == DetectedActivity.RUNNING && nextHighest != lastActivity) { 
         Log.d(TAG, "On Running " + mostProbableActivity.getConfidence()); 
         //Send Notification To User 
//      NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
//      builder.setContentText("Running"); 
//      builder.setSmallIcon(R.drawable.elaxer_x); 
//      builder.setContentTitle("Elaxer"); 
//      NotificationManagerCompat.from(this).notify(0, builder.build()); 
         if (apiClient.isConnected()) { 
          updateLocationSetting(3 * 60 * 1000, 2 * 60 * 1000, LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
          lastActivity = nextHighest; 
         } 
        } 
        else if (nextHighest.getConfidence() >= 75 && nextHighest != lastActivity) { 
         Log.d(TAG, "On Walking " + mostProbableActivity.getConfidence()); 
         //Send Notification To User 
//      NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
//      builder.setContentText("Let's Walk"); 
//      builder.setSmallIcon(R.drawable.elaxer_x); 
//      builder.setContentTitle("Elaxer"); 
//      NotificationManagerCompat.from(this).notify(0, builder.build()); 

         if (apiClient.isConnected()) { 
          updateLocationSetting(3 * 60 * 1000, 2 * 60 * 1000, LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
          lastActivity = nextHighest; 
         } 
        } 
        //Send Notification To User 
//     NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
//     builder.setContentText("On Foot"); 
//     builder.setSmallIcon(R.drawable.elaxer_x); 
//     builder.setContentTitle("Elaxer"); 
//     NotificationManagerCompat.from(this).notify(0, builder.build()); 
       } 
       break; 
      case DetectedActivity.STILL: 
       Log.d(TAG, "On Still " + mostProbableActivity.getConfidence()); 
       if (mostProbableActivity.getConfidence() >= 75 && mostProbableActivity != lastActivity) { 
        //Send Notification To User 
//     NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
//     builder.setContentText("Still"); 
//     builder.setSmallIcon(R.drawable.elaxer_x); 
//     builder.setContentTitle("Elaxer"); 
//     NotificationManagerCompat.from(this).notify(0, builder.build()); 

        if (apiClient.isConnected()) { 
         updateLocationSetting(5 * 60 * 60 * 1000, 3 * 60 * 60 * 1000, LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
         lastActivity = mostProbableActivity; 
        } 
       } 
       break; 
      case DetectedActivity.TILTING: 
       Log.d(TAG, "On Tilting " + mostProbableActivity.getConfidence()); 
       if (mostProbableActivity.getConfidence() >= 75 && mostProbableActivity != lastActivity) { 
        //Send Notification To User 
//     NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
//     builder.setContentText("Tilting"); 
//     builder.setSmallIcon(R.drawable.elaxer_x); 
//     builder.setContentTitle("Elaxer"); 
//     NotificationManagerCompat.from(this).notify(0, builder.build()); 

        if (apiClient.isConnected()) { 
         updateLocationSetting(3 * 60 * 1000, 2 * 60 * 1000, LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
         lastActivity = mostProbableActivity; 
        } 
       } 
       break; 
//   case DetectedActivity.WALKING: 
//    Log.d(TAG, "On Walking " + mostProbableActivity.getConfidence()); 
//    if (mostProbableActivity.getConfidence() >= 75) { 
//     //Send Notification To User 
//     NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
//     builder.setContentText("Let's Walk"); 
//     builder.setSmallIcon(R.drawable.elaxer_x); 
//     builder.setContentTitle("Elaxer"); 
//     NotificationManagerCompat.from(this).notify(0, builder.build()); 
// 
//     if (apiClient.isConnected()) { 
//      updateLocationSetting(3 * 60 * 1000, 2 * 60 * 1000, LocationRequest.PRIORITY_HIGH_ACCURACY); //5 hours= hours * 60 min*60 sec* 1000 milliseconds 
//     } 
//    } 
//    break; 
      case DetectedActivity.UNKNOWN: 
       Log.d(TAG, "UnKnown " + mostProbableActivity.getConfidence()); 
       lastActivity = mostProbableActivity; 
       break; 
     } 
    } 

    private void updateLocationSetting(int Interval, int FastestInterval, int LocationAccuracy) { 
     LocationRequest request = new LocationRequest(); 
     request.setInterval(Interval); 
     request.setFastestInterval(FastestInterval); 
     request.setPriority(LocationAccuracy); 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) { 
      //TODO DO SOMETHING HERE! 
      return; 
     } 
     LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, request, pendingIntent); 
    } 
} 

Và đây sẽ là IntentService để sử dụng thay vì sử dụng AsyncTask bạn đang sử dụng:

public class YourIntentService extends IntentService { 

    public YourIntentService() { 
     super("YOUR_INTENT_SERVICE"); 
    } 

    @Override 
    protected void onHandleIntent(@Nullable Intent intent) { 
     if (intent != null) { 
      if (LocationResult.hasResult(intent)) { 
       LocationResult result = LocationResult.extractResult(intent); 
       Location location = result.getLastLocation(); 
       Log.d("YourIntentService", "Got new location: " + location); 
      } 
      else if (intent.hasExtra("lastKnown")) { 
       Location location = intent.getParcelableExtra("lastKnown"); 
       Log.d("YourIntentService", "Got last known location: " + location); 
      } 
      else if (LocationAvailability.hasLocationAvailability(intent)) { 
       LocationAvailability locationAvailability = LocationAvailability.extractLocationAvailability(intent); 
       Log.d("YourIntentService", "Location Availability: " + locationAvailability.isLocationAvailable()); 
      } 
     } 
    } 
} 

Dịch vụ ý định này có thể xử lý các yêu cầu mạng chặn miễn là chúng được gọi trong số onHandleIntent.

Tôi đã sửa đổi mã handleDetectedActivity một chút sao cho trên mọi cập nhật hoạt động, cập nhật vị trí mới không xảy ra.


Trước hết, tôi sẽ không đề nghị bạn sử dụng một IntentService cách tại bạn đang có, như là dịch vụ sẽ bị giết khi nó thoát onHandleIntent, mà có thể gây ra rất nhiều vấn đề kể từ khi bạn đang dựa vào callbacks. Tất cả điều này nên được đưa vào một số Service thay thế.

Đối với việc xử lý các cập nhật vị trí dựa trên nhận dạng hoạt động, tôi đã tìm thấy thư viện đẹp này giúp đơn giản hóa việc này và khá dễ sử dụng.https://github.com/mrmans0n/smart-location-lib

Dưới đây là ví dụ về cách sử dụng thư viện có cập nhật vị trí dựa trên kết quả hoạt động.

SmartLocation.with(this).location(new LocationBasedOnActivityProvider(new LocationBasedOnActivityProvider.LocationBasedOnActivityListener() { 
    @Override 
    public LocationParams locationParamsForActivity(DetectedActivity detectedActivity) { 
     if (detectedActivity.getConfidence() >= 75) { 
      LocationParams.Builder builder = new LocationParams.Builder(); 
      switch (detectedActivity.getType()) { 
       case DetectedActivity.IN_VEHICLE: 
        builder.setInterval(/*Interval*/) 
          .setAccuracy(/*Locaiton Accuracy*/); 
        break; 

       case DetectedActivity.ON_BICYCLE: 
        /* So on and so forth.... */ 

        break; 
      } 
      return builder.build(); 
     } 
     return null; 
    } 
})).start(new OnLocationUpdatedListener() { 
    @Override 
    public void onLocationUpdated(Location location) { 
     //Do what you need here. 
    } 
}); 

này nên được thả vào một Service trong onStart chức năng, với onStartCommand thay đổi xử lý dựa trên các tính năng bổ sung ý bạn cung cấp. Bạn cũng có thể sử dụng thư viện này để có được vị trí đã biết cuối cùng và để có được một bản sửa lỗi duy nhất.

Điều cuối cùng, tôi khuyên bạn nên rời khỏi số AsyncTask nếu bạn đang chuyển ngữ cảnh cho nó. Thay vào đó hãy sử dụng IntentService, vì chức năng onHandleIntent được chạy trong một chuỗi nền và bạn có thể sử dụng ngữ cảnh của IntentService để thực hiện bất kỳ tác vụ nào bạn cần với nó. Bạn có thể chuyển đối tượng Location như một mục đích bổ sung khi bạn bắt đầu IntentService.

+0

U có thể đúng. Nhưng tôi đã kiểm tra lib này trên github và chúng tôi không muốn sử dụng bất kỳ lib.This bổ sung sẽ được sửa chữa bởi một số logic mà không cần bất kỳ thư viện bổ sung – androidXP

+0

Logic mã của bạn nói kiểm tra xem hoạt động cuối cùng không bằng hiện tại. Nếu thay đổi hoạt động sau đó nhập vào scope.I phải không? xin vui lòng rõ ràng cho tôi nếu tôi sai – androidXP

+0

Như trong mã bạn sử dụng lastActivity (DetectedActivity) nếu nó giống như cuối cùng. Vì vậy, nó sẽ được null cuz của nó không khởi tạo và đặt giá trị sau khi nó – androidXP

Các vấn đề liên quan