2017-03-08 77 views
1

您好每一個我有Myservice一個不斷變化的值,它是速度和距離,我計算它在onLocationChanged的服務,我想在片段TextView顯示變化值,我已經嘗試廣播它並與broadcastReceiver接收它,但它不適用於KitKat(API 19), 所以我試圖綁定它,但它給了我錯誤的值,請任何幫助 這裏是一個locationListener在Service Class如何從onLocationChanged服務綁定值Fragemnt

public class MyLocationListener implements LocationListener { 

     public void onLocationChanged(final Location loc) { 
      Location lastLocation; 
      if (loc != null) { 
       Double d1; 
       Long t1; 
       speed = 0.0; 
       d1 = 0.0; 
       t1 = 0l; 
       currentLocation = loc; 
       lastLocation = currentLocation; 

       // two arrays for position and time. 
       positions = new Double[data_points][2]; 
       times = new Long[data_points]; 

       positions[counter][0] = loc.getLatitude(); 
       positions[counter][1] = loc.getLongitude(); 
       times[counter] = loc.getTime(); 

       try { 
        // get the distance and time between the current position, and the previous position. 
        // using (counter - 1) % data_points doesn't wrap properly 
        d1 = distance(positions[counter][0], positions[counter][1], positions[(counter + (data_points - 1)) % data_points][0], positions[(counter + (data_points - 1)) % data_points][1]); 
        t1 = times[counter] - times[(counter + (data_points - 1)) % data_points]; 
       } catch (NullPointerException e) { 
       } 

       if (loc.hasSpeed()) { 
        speed = loc.getSpeed() * 1.0; // need to * 1.0 to get into a double for some reason... 
       } else { 
        speed = d1/t1; // m/s 
       } 
       counter = (counter + 1) % data_points; 
       speed = speed * 3.6d; 
       distanceList = new ArrayList<>(); 
       Log.i("**********", "Location changed"); 
       myLocation = new LatLng(loc.getLatitude(), loc.getLongitude()); 
       if (isBetterLocation(loc, previousBestLocation)) { 
        loc.getLatitude(); 
        loc.getLongitude(); 
        for (LatLng location : cameraLocation) { 
//      closestCamera = location; 
//      smallestDistance = distance; 
//      Log.e("distanceTest", distance + ""); 
//      Log.d("closestCamera" , location+""); 
//      distanceList.add(CalculationByDistance(myLocation, location)); 
//      distance = Collections.min(distanceList); 
         double distanceFromLastLocation = CalculationByDistance(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), location); 
         double distanceFromCurrentLocation = CalculationByDistance(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), location); 
         if (distanceFromCurrentLocation < distanceFromLastLocation) { 
          continue; // User is going away from location i.e location is behind user. No need to calculate distance between user and cameraLocation. 
         } 
         distanceList.add(CalculationByDistance(myLocation, location)); 
         if (Collections.min(distanceList) == distanceFromCurrentLocation) { 
          // this location is nearest amongst all the cameraLocations. 
          smallestDistance = distanceFromCurrentLocation; 
          closestCamera = location; 
         } 

        } 

        DecimalFormat df = new DecimalFormat("###.##"); 
        String distanceString = df.format(smallestDistance); 
        intent.setAction(MY_ACTION); 
        speedInt = speed.intValue(); 
        intent.putExtra("speed", speed.intValue()); 
        intent.putExtra("Latitude", loc.getLatitude()); 
        intent.putExtra("Longitude", loc.getLongitude()); 
        intent.putExtra("distance", distanceString); 
        intent.putExtra("Provider", loc.getProvider()); 
        sendBroadcast(intent); 
        if (speed > 25) { 
         // createNotification(R.raw.camera_alert , String.valueOf(R.string.cameraAlertString)); 
        } 
        sendNotification(); 

       } 



      } 
     } 
//******************************************************************************************************* 

     public void onProviderDisabled(String provider) { 
      Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show(); 
     } 


     public void onProviderEnabled(String provider) { 
      Toast.makeText(getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show(); 
     } 


     public void onStatusChanged(String provider, int status, Bundle extras) { 

     } 

    } 

我想將smallestDistance和speed.intValue()綁定到Fragment,這裏是bi nder類。

private final IBinder binder = new TaskBinder(); 


    public class TaskBinder extends Binder { 
     public GPSService getService() { 
      return GPSService.this; 
     } 
    } 

,並在這裏,我嘗試過的方法來綁定

public String getDestance(){ 
     DecimalFormat df = new DecimalFormat("###.##"); 
     String distanceString = df.format(smallestDistance); 
     return distanceString ; 
    } 
    public int getSpeed(){ 
     return speedInt ; 
    } 

,我如何連接服務片段

private ServiceConnection connection = new ServiceConnection() { 
     @Override 
     public void onServiceConnected(ComponentName className, IBinder service) { 
      binder = (GPSService.TaskBinder) service; 
      localService = binder.getService(); 
      isBound = true; 
      Log.d("connect", "onServiceConnected"); 
      String nearestCamera = localService.getDestance(); 
      int speed = localService.getSpeed(); 
      Log.e("w speedd" , speed+""); 
      Log.e("w nearestCamera" , nearestCamera+""); 
      nearestCameraTxt.setText(nearestCamera+" Km/m"); 
      carSpeedTxt.setText(speed+"\n Km/h"); 

     } 
     @Override 
     public void onServiceDisconnected(ComponentName arg0) { 
      isBound = false; 
      Log.d("notConnect", "onServiceNotConnected"); 

     } 
    }; 
+0

也許添加一些代碼和日誌將是一個不錯的主意! – Ibrahim

+0

我更新我的問題,請你回顧一下 –

回答

0

在您的片段試試這個:

GPSTracker mService; //define service class; 
boolean mBound = false; 

現在打電話給Bind s ervice方法:使用

/** 
* Defines callbacks for service binding, passed to bindService() 
*/ 
private ServiceConnection mConnection = new ServiceConnection() { 

    @Override 
    public void onServiceConnected(ComponentName className, 
            IBinder service) { 
     // We've bound to LocalService, cast the IBinder and get LocalService instance 
     GPSTracker.MyBinder binder = (GPSTracker.MyBinder) service; 
     mService = binder.getService(); 
     mBound = true; 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName arg0) { 
     mBound = false; 
    } 
}; 

獲得價值:

if (mBound) { 
     // Call a method from the LocalService. 
     // However, if this call were something that might hang, then this request should 
     // occur in a separate thread to avoid slowing down the activity performance. 
     Double latitude = mService.getLatitude(); 
     Double longitude = mService.getLongitude(); 
     Toast.makeText(getActivity(), "Received", Toast.LENGTH_LONG).show(); 
    } 

在服務類中重寫此方法:

@Override 
public IBinder onBind(Intent arg0) { 
    return mBinder; 
} 

public class MyBinder extends Binder { 
    GPSTracker getService() { //GPSTracker is the service class name 
     return GPSTracker.this; 
    } 
} 

public Double getLatitude_s() { 
    return latitude; 
} 

public Double getLongitude_s() { 
    return longitude; 
} 

而且u需要使用您的片段類啓動服務:

getActivity().startService(new Intent(getActivity(), GPSTracker.class)); 
+0

我已經這樣做了,但它給了我錯誤的價值,那麼廣播接收機做什麼 –

+0

你怎麼知道它給出錯誤的價值?......它應該根據你的服務實現給予價值。 。 – rafsanahmad007

+0

我添加一些代碼,你可以檢查它從onLocationChanged廣播發送,所以它保持更新的價值和廣播它,但onBind我必須做我自己的方法來綁定值,我不能在onLocationChanged方法 –

0

Y您可以使用EventBus在ServiceFragment之間進行通信。

添加依賴於搖籃:

compile 'org.greenrobot:eventbus:3.0.0'

創建事件對象,將舉行您的位置值:

public class LocationUpdateEvent { 
    public final Location location; 

    public LocationUpdateEvent(final Location location) { 
    this.location = location; 
    } 

    public Location getLocation() { 
    return location; 
    } 
} 

從服務的onLocationChanged()發送事件:

EventBus.getDefault().post(new LocationUpdateEvent(latLng)); 

訂閱事件片段:

@Subscribe 
public void onLocationUpdateEvent(LocationUpdateEvent event) { 
    int speed = event.getLocation().getSpeed() 
    // set speed variable to TextView as you do now in your code 
    }; 

@Override 
public void onStart() { 
    super.onStart(); 
    EventBus.getDefault().register(this); // it's important to register the bus 
} 

@Override 
public void onStop() { 
    super.onStop(); 
    EventBus.getDefault().unregister(this); // unregister is nessesary 
} 
+0

創建公共方法我明白的想法,但如何從它發送距離和速度,我添加了一些代碼,請你告訴我如何最後分配速度和距離文本視圖? –

+0

@ReemAziz更新了答案。 – Val