2016-02-26 51 views
0

我遇到了這個問題,我的Android位置始終爲空,但它似乎只發生在我的應用從後臺轉到前臺時發生。這裏是我的代碼:從前景到背景後,位置始終爲空?

Public.java:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    String userId = AccessToken.getCurrentAccessToken().getUserId(); 

    //Open DB and get freinds from db & posts. 
    datasource = new FriendsDataSource(getContext()); 
    datasource.open(); 
    postsDataSource = new PostsDataSource(getContext()); 
    postsDataSource.open(); 

    fragmentView = inflater.inflate(R.layout.public_tab, container, false); 

    populateNewsFeedList(fragmentView); 

    return fragmentView; 
} 


public void populateNewsFeedList(View fragmentView) { 
    RecyclerView rv = (RecyclerView) 
    fragmentView.findViewById(R.id.rv_public_feed); 
    LinearLayoutManager llm = new LinearLayoutManager(getContext()); 
    rv.setLayoutManager(llm); 
    Location location = checkLocation(); 
    //Set a 24140.2 meter, or a 15 mile radius. 
    adapter = new PostRecyclerViewAdapter(postsDataSource.getAllPublicPosts(location.getLatitude(), location.getLongitude(), 24140.2), getContext(), true); 
    rv.setAdapter(adapter); 
} 

private Location checkLocation() { 
    Location location = LocationService.getLastLocation(); 
    if(location == null){ 
     System.out.println("Null location"); 
     LocationService.getLocationManager(getContext()); 
     //Connect to google play services to get last location 
     LocationService.getGoogleApiClient().connect(); 
     location = LocationService.getLastLocation(); 
     return location; 
    } 
    else { 
     return location; 
    } 
} 

LocationService.java:

public class LocationService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 
    //Google Location Services API 
    private static LocationService instance = null; 
    public static GoogleApiClient googleApiClient; 
    private static Location lastLocation; 
    LocationManager locationManager; 
    Context context; 

    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1; 


    /** 
    * Singleton implementation 
    * @return 
    */ 
    public static LocationService getLocationManager(Context context)  { 
     if (instance == null) { 
      instance = new LocationService(context); 
     } 
     return instance; 
    } 

    /** 
    * Local constructor 
    */ 
    private LocationService(Context context)  { 
     this.context = context; 
     initLocationService(context); 
    } 

    /** 
    * Sets up location service after permissions is granted 
    */ 
    private void initLocationService(Context context) { 
     if (googleApiClient == null) { 
      googleApiClient = new GoogleApiClient.Builder(context) 
        .addConnectionCallbacks(this) 
        .addOnConnectionFailedListener(this) 
        .addApi(com.google.android.gms.location.LocationServices.API) 
        .build(); 
     } 

    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     try { 
      lastLocation = LocationServices.FusedLocationApi.getLastLocation(
        googleApiClient); 
     } catch (SecurityException e){ 
      System.out.println("Security Exception: " + e); 
     } 

    } 

    public static Location getLastLocation(){ 
     return lastLocation; 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    protected static void onStart() { 
     googleApiClient.connect(); 
    } 

    protected void onStop() { 
     googleApiClient.disconnect(); 
    } 

    public static GoogleApiClient getGoogleApiClient() { 
     return googleApiClient; 
    } 
} 

的問題是,即使我進入checkLocation()功能(這是我實現的嘗試初始化我的位置服務,以防止我的位置爲空)在Public.java,我看到我的LocationService正確初始化和一切,每當我打電話Location.getLastLocation(),我總是返回一個空值。我真的不知道爲什麼會發生這種情況,這似乎只發生在我的應用從後臺轉到前臺時發生。任何幫助將不勝感激,謝謝!

回答

0

試試這個,

private LocationManager locationManager; 
private String provider; 
private Location location; 
private boolean isGPSEnabled; 
private static boolean isNetworkEnabled; 
public static double lat=0.0; 
public static double lng=0.0; 


public void checkLocation(Activity activity) { 
    locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE); 
    Criteria c = new Criteria(); 
    provider = locationManager.getBestProvider(c, false); 
    location = getLocation(activity); 
    locationManager.requestLocationUpdates(provider, 400, 1, this); 
    locationManager.removeUpdates(this); 

    if (location != null) { 
     // get latitude and longitude of the location 
     onLocationChanged(location); 

    } else { 
     Log.d("TAG","Unable to find Location"); 
    } 
} 



public Location getLocation(Activity activity) { 
    try { 
     locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 400, 0, this); 
       Log.d("Network", "Network Enabled"); 
       if (locationManager != null) { 
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         lat = location.getLatitude(); 
         lng = location.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 0, this); 
        Log.d("GPS", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          lat = location.getLatitude(); 
          lng = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 

    } catch (SecurityException e) { 
     Log.e("PERMISSION_EXCEPTION","PERMISSION_NOT_GRANTED"); 
    }catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return location; 
} 

@Override 
public void onLocationChanged(Location location) { 
    lat = location.getLatitude(); 
    lng = location.getLongitude(); 
} 

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

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 
+0

我會在地方LocationService.java的使用呢?或在Public.java中? – user1871869

+0

你可以在public.java中添加它並調用checkLocation()方法 –

+0

這似乎適用於我。有什麼機會,你會碰巧知道我的代碼爲什麼不工作?謝謝! :) – user1871869