2015-01-27 3 views
-1

사용자 경로의 초기 지점을 안정화하기 위해 현재 위치를 얻으려고합니다. 코드가 실행 중이지만 GoogleApiClient가 연결되지 않습니다.android - CurrentLocation을 가져올 수 없습니다.

내가 뭘 잘못하고 있는지 모르겠다. 어떤 도움을 주시면 감사하겠습니다.

감사

package com.csusbCampusTracking; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; 
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; 

import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 
import com.google.android.gms.location.LocationListener; 

import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter; 
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; 
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; 


import com.google.android.gms.maps.CameraUpdateFactory; 
import com.google.android.gms.maps.SupportMapFragment; 
import com.google.android.gms.maps.model.BitmapDescriptorFactory; 
import com.google.android.gms.maps.model.LatLng; 
import com.google.android.gms.maps.model.LatLngBounds; 
import com.google.android.gms.maps.model.Marker; 
import com.google.android.gms.maps.model.MarkerOptions; 


import android.os.Build; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.SystemClock; 

import android.annotation.SuppressLint; 
import android.content.Intent; 
import android.graphics.Color; 
import android.location.Location; 
import android.support.v4.app.FragmentActivity; 

import android.text.SpannableString; 
import android.text.style.ForegroundColorSpan; 

import android.view.View; 
import android.view.ViewTreeObserver.OnGlobalLayoutListener; 
import android.view.animation.BounceInterpolator; 
import android.view.animation.Interpolator; 

import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast; 

/** 
* An activity that creates a map with some initial options. 
*/ 
public class displayMap extends FragmentActivity implements 
OnMarkerClickListener, 
OnInfoWindowClickListener, 
ConnectionCallbacks, 
OnConnectionFailedListener, 
LocationListener 

{ 
    public double latitud; 
    public double longitud; 
    public LatLng ORIGIN; // = new LatLng(34.02143074239393, -117.61349469423294); 
    public LatLng DESTINY; 
    private GoogleMap mMap; 
    private Marker mDestiny; 
    private Marker mOrigin; 
    private Marker mLastSelectedMarker; // keeps track of last selected marker 

    private GoogleApiClient mGoogleApiClient; 

    // These settings are the same as the settings for the map. They will in fact provide updates 
    // at the maximal rates currently possible. 
    private static final LocationRequest REQUEST = LocationRequest.create() 
    .setInterval(5000)   // 5 seconds 
    .setFastestInterval(16) // 16ms = 60fps 
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 


    /*************************** 
    * On CREATE method  * 
    ***************************/ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.map); 

    setUpGoogleApiClientIfNeeded(); 
    mGoogleApiClient.connect(); 
    if (mGoogleApiClient.isConnected()){ 
     System.out.println("Conected *****"); 
    }else { 
     System.out.println("Not conected *****"); 
    } 
    if (mLastSelectedMarker != null && mLastSelectedMarker.isInfoWindowShown()) { 
     // Refresh the info window when the info window's content has changed. 
     mLastSelectedMarker.showInfoWindow(); 
    } 
    setUpMapIfNeeded(); 
    } 

    /******************************** 
    * setUpGoogleApiClientIfNeeded * 
    * ******************************/ 
    private void setUpGoogleApiClientIfNeeded() { 
    if (mGoogleApiClient == null) { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
     .addApi(LocationServices.API) 
     .addConnectionCallbacks(this) 
     .addOnConnectionFailedListener(this) 
     .build(); 
    } 
    } 

    /******************************** 
    * setUpMapIfNeeded    * 
    * ******************************/ 
    private void setUpMapIfNeeded() { 
    // Do a null check to confirm that we have not already instantiated the map. 
    if (mMap == null) { 
     // Try to obtain the map from the SupportMapFragment. 
     mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) 
     .getMap(); 
     // Check if we were successful in obtaining the map. 
     if (mMap != null) { 
      mMap.setMyLocationEnabled(true); 
      setUpMap(); 
     } 
    } 
    } 

    /******************************** 
    * setUpMap      * 
    * ******************************/ 
    private void setUpMap() { 

    double longitude = getLong(); // target 
    double latitude = getLat(); // info. 

    getLocation(ORIGIN); 
    ORIGIN = new LatLng(34.02143074239393, -117.61349469423294); 
    DESTINY = new LatLng(latitude, longitude); 
    // Hide the zoom controls as the button panel will cover it. 
    mMap.getUiSettings().setZoomControlsEnabled(false); 
    addMarkersToMap(); 

    // customizing the info window. 
    mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter()); 

    // Set listeners for marker events. 
    mMap.setOnMarkerClickListener(this); // to display infowindow 
    mMap.setOnInfoWindowClickListener(this); // to display extra info 

    // Pan to see all markers in view. 
    // Cannot zoom to bounds until the map has a size. 
    final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView(); 
    if (mapView.getViewTreeObserver().isAlive()) { 
     mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
     @SuppressWarnings("deprecation") // We use the new method when supported 
     @SuppressLint("NewApi") // We check which build version we are using. 
     @Override 
     public void onGlobalLayout() { 
      LatLngBounds bounds = new LatLngBounds.Builder() // defines the map bounds 
      .include(DESTINY) 
      .include(ORIGIN) 
      .build(); 
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { 
      mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
      } else { 
      mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this); 
      } 
      mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50)); 
     } 
     }); 
    } 
    } // end setUpMap 


    /************************************************* 
    *    ORIGIN2      *      
    * Retrieves current latitude and longitude  * 
    *************************************************/ 
    public LatLng getLocation(LatLng ORIGIN2) { 

    setUpGoogleApiClientIfNeeded(); 
    mGoogleApiClient.connect(); 
    if (mGoogleApiClient.isConnected()){ 
     System.out.println("Conected 8888"); 
    }else { 
     System.out.println("Not Conected 8888"); 
    } 

    if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { 
     String msg = "Location = " 
     + LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
     System.out.println("We are mGoogleApiClient "); 
     Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); 
    } else { 
     System.out.println("We are not mGoogleApiClient "); 
    } 
    return ORIGIN2; 
    } 


    /********************************************************* 
    * Implementation of {@link OnConnectionFailedListener}. * 
    *********************************************************/ 
    @Override 
    public void onConnectionFailed(ConnectionResult result) { 
     // Do nothing 
    } 


    /************************************* 
    *    addMarker   * 
    *************************************/ 
    private void addMarkersToMap() { 
    // initial position marker 
    String targetTitle = getTargetTitle(); 
    mOrigin = mMap.addMarker(new MarkerOptions() 
    .position(ORIGIN) 
    .title("Origin") 
    .snippet("Point of Start") 
    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))); 

    double latitude = getLat(); 
    double longitude = getLong(); 

    DESTINY = new LatLng(latitude, longitude); 
    // target position marker 
    mDestiny = mMap.addMarker(new MarkerOptions() 
    .position(DESTINY) 
    .title("Destiny") 
    .snippet(targetTitle) 
    .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow))); 
    } 

    /************************************* 
    *   checkReady    * 
    *************************************/ 
    private boolean checkReady() { 
    if (mMap == null) { 
     Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show(); 
     return false; 
    } 
    return true; 
    } 

    /************************************* 
    *   onToggleFlat   * 
    *************************************/ 
    public void onToggleFlat(View view) { 
    if (!checkReady()) { 
     return; 
    } 
    } 

    /************************************* 
    *   onResume    * 
    *************************************/ 
    @Override 
    protected void onResume() { 
    super.onResume(); 
    setUpGoogleApiClientIfNeeded(); 
    mGoogleApiClient.connect(); 
    setUpMapIfNeeded(); 
    } 

    /************************************* 
    *   onPause     * 
    *************************************/ 
    @Override 
    public void onPause() { 
     super.onPause(); 
     if (mGoogleApiClient != null) { 
      mGoogleApiClient.disconnect(); 
     } 
    } 

    /******************************* 
    * Callback (generated)  * 
    *******************************/ 
    @Override 
    public void onConnected(Bundle connectionHint) { 
    LocationServices.FusedLocationApi.requestLocationUpdates(
    mGoogleApiClient, REQUEST, (LocationListener) this); // LocationListener 
    } 


    /************************************* 
    *   onMarkerClick   * 
    *************************************/ @Override 
    public boolean onMarkerClick(final Marker marker) { 
    if (marker.equals(mDestiny)) { 
     // This causes the marker at target to bounce into position when it is clicked. 
     final Handler handler = new Handler(); 
     final long start = SystemClock.uptimeMillis(); 
     final long duration = 1500; 
     final Interpolator interpolator = new BounceInterpolator(); 

     handler.post(new Runnable() { 
     @Override 
     public void run() { 
      long elapsed = SystemClock.uptimeMillis() - start; 
      float t = Math.max(1 - interpolator.getInterpolation((float) elapsed/duration), 0); 
      marker.setAnchor(0.5f, 1.0f + 2 * t); 
      if (t > 0.0) { 
      // Post again 16ms later. 
      handler.postDelayed(this, 16); 
      } 
     } 
     }); 
    } 

    mLastSelectedMarker = marker; 
    // We return false to indicate that we have not consumed the event and that we wish 
    // for the default behavior to occur (which is for the camera to move such that the 
    // marker is centered and for the marker's info window to open, if it has one). 
    return false; 
    } 


    /************************************* 
    *  onInfoWindowClick   * 
    *************************************/ 
    @Override 
    public void onInfoWindowClick(Marker marker) { 
    Toast.makeText(this, "Click Info Window", Toast.LENGTH_SHORT).show(); 
    } 


    /************************************* 
    *  MyLocationListener   * 
    *************************************/ 
    public class MyLocationListener implements LocationListener { 
    @Override 
    public void onLocationChanged(Location loc) { 
     loc.getLatitude(); 
     loc.getLongitude(); 
    } 

    public void onStatusChanged(String provider, int status, Bundle extras) { 
    // TODO Auto-generated method stub 

    } 

    public void onProviderEnabled(String provider) { 
    // TODO Auto-generated method stub 

    } 

    public void onProviderDisabled(String provider) { 
    // TODO Auto-generated method stub 
    } 
    } 

    /**************************************** 
    * This defines the marker's info  * 
    * two view texts and a snippet   * 
    ****************************************/ 

    private void render(Marker marker, View view) { 
    int badge; 
    // It won't work with ==> == Must use==> equals() 
    if (marker.equals(mOrigin) | marker.equals(mDestiny)) { 
     badge = R.drawable.badge_csusb; 
    } else { 
     // Passing 0 to setImageResource will clear the image view. 
     badge = 0; 
    } 
    ((ImageView) view.findViewById(R.id.badge)).setImageResource(badge); 
    String title = marker.getTitle(); 
    TextView titleUi = ((TextView) view.findViewById(R.id.title)); 
    if (title != null) { 
     // SpannableString allows to edit the formatting of the text. 
     SpannableString titleText = new SpannableString(title); 
     titleText.setSpan(new ForegroundColorSpan(Color.RED), 0, titleText.length(), 0); 
     titleUi.setText(titleText); 
    } else { 
     titleUi.setText(""); 
    } 

    String snippet = marker.getSnippet(); 
    TextView snippetUi = ((TextView) view.findViewById(R.id.snippet)); 
    if (snippet != null && snippet.length() > 12) { 
     SpannableString snippetText = new SpannableString(snippet); 
     snippetText.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 12, 0); 
     snippetText.setSpan(new ForegroundColorSpan(Color.BLUE), 12, snippet.length(), 0); 
     snippetUi.setText(snippetText); 
    } else { 
     snippetUi.setText(""); 
    } 
    } // end of marker info 


    class CustomInfoWindowAdapter implements InfoWindowAdapter { 
    private final View mWindow; 
    CustomInfoWindowAdapter() { 
     mWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null); 
    } 

    @Override 
    public View getInfoWindow(Marker marker) { 
     render(marker, mWindow); 
     return mWindow; 
    } 

    @Override 
    public View getInfoContents(Marker arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
    } // end of CustomInfoWindowAdapter 


    public double getLat() { 
    Intent i= getIntent(); 
    double latitude = i.getExtras().getDouble("locLat"); 
    return latitude; 
    } 

    public double getLong() { 
    Intent i= getIntent(); 
    double longitude = i.getExtras().getDouble("locLong"); 
    return longitude; 
    } 

    public String getTargetTitle() { 
    Intent i= getIntent(); 
    String targetTitle = i.getExtras().getString("locDesc"); 
    return targetTitle; 
    } 


    public void onLocationChanged(Location location) { 
    // TODO Auto-generated method stub 
    } 


    public void onStatusChanged(String provider, int status, Bundle extras) { 
    // TODO Auto-generated method stub 
    } 


    public void onProviderEnabled(String provider) { 
    // TODO Auto-generated method stub 
    } 


    public void onProviderDisabled(String provider) { 
    // TODO Auto-generated method stub 
    } 


    @Override 
    public void onConnectionSuspended(int cause) { 
    // TODO Auto-generated method stub 
    } 

}// end of program 
// Java Document 
+0

LogCat의 오류? –

+0

오류가 없으므로 연결되지 않습니다. 프로그램을 추적하기 위해 플래그로 사용하고있는 "연결되지 않았다"라는 메시지를 출력합니다. – francisqueins

+0

이 프로그램으로 GPS를 에뮬레이션하려고하는데, 이제는 대상 운명을 선택할 수있는 지점까지 가야합니다. 좌표. 소스 좌표를 강제로 ORIGIN = new LatLng (34.02143074239393, -117.61349469423294); 이 줄을 주석 처리 할 때 프로그램이 실패하고 catlog는 다음과 같습니다 : – francisqueins

답변

0

나는 경우 다른 사람이 같은 문제를 가지고 그냥이 일을 답변 해 드리겠습니다, 코드 작업을 수행합니다. 그러나 장치가 위성에 연결될 수 없으면 성공하지 못했다는 메시지를 보내지 않습니다. 제 경우에는 제 집 밖에있는 프로그램을 시험해보고 효과가있었습니다.

건배

관련 문제