2017-03-08 9 views
1

안녕하세요. onLocationChanged에서 서비스를 계산하는 속도와 거리가 각각 Myservice 인 모든 사람에게 안녕하세요. TextView에 변경 값을 표시하고 싶습니다. 나는 그것을 함께 방송하고 broadcastReceiver으로 수신하려고 시도하지만 KitKat (API 19), 과 함께 작동하지 않았으므로 바인딩하려고 시도했지만 잘못된 값을 주었다. 어떤 도움을 주겠습니까 여기는 서비스 클래스의 locationListener입니다.서비스에서 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은(), 여기에 양방향입니다 바인딩 할 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 호출 서 비 스 방법 :

/** 
* 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 메서드에서 public 메서드를 만들지 못합니다. –

0

EventBus를 사용하여 ServiceFragment 사이에서 통신 할 수 있습니다.

Gradle을에 의존성을 추가

public class LocationUpdateEvent { 
    public final Location location; 

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

    public Location getLocation() { 
    return location; 
    } 
} 

서비스의 onLocationChanged()에서 이벤트를 보내기 :

compile 'org.greenrobot:eventbus:3.0.0'

위치 값을 보관 유지하는 이벤트 객체를 생성

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