2017-03-17 47 views
0

我遇到了一些麻煩,可以提供一些幫助。我有一個MapsActivity和一個LocationHelper類,但是當加載MapsActivity時,我會看到下面列出的錯誤。'onCreate()'前系統服務不可用的活動''

MapsActivity -

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { 

private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; 
private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 2; 
private GoogleMap mMap; 
private LocationHelper locationHelper; 
private LatLng location; 
private boolean onCreateFinished = false; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    onCreateFinished = true; 
    setContentView(R.layout.activity_maps); 
    // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 

    //instantiates LocationHelper for use in this activity 
    locationHelper = new LocationHelper(this); 
    //runs startConnection from LocationHelper class 
    locationHelper.startConnection(); 

    //starts map 
    mapFragment.getMapAsync(this); 
} 

@Override 
public void onMapReady(GoogleMap googleMap) { 

    mMap = googleMap; 
    // Add a marker in Sydney and move the camera 
    LatLng sydney = new LatLng(-34, 151); 
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); 
    //mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); 
} 

//sets map markers 
public void setMapMarkers(){ 
    //runs checkLocation from LocationHelper class 
    locationHelper.checkLocation(); 
    location = new LatLng(locationHelper.mLatitude, locationHelper.mLongitude); 

    LatLng currentLocation = new LatLng(location.latitude, location.longitude); 
    mMap.addMarker(new MarkerOptions().position(currentLocation).title("Your Location")); 
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation)); 
} 

@Override 
protected void onStart() { 
    locationHelper.mGoogleApiClient.connect(); 
    super.onStart(); 
} 
@Override 
protected void onResume() { 
    super.onResume(); 
    if(onCreateFinished == true){ 
     setMapMarkers(); 
    }else{ 
     Toast.makeText(this, "onCreate not finished..", Toast.LENGTH_SHORT).show(); 
    } 

} 
@Override 
protected void onStop() { 
    locationHelper.mGoogleApiClient.disconnect(); 
    //LocationManager.removeUpdates(); 
    super.onStop(); 
} 

LocationHelper類 -

public class LocationHelper extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 

//private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; 
//private static final int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 2; 
GoogleApiClient mGoogleApiClient; 
private LocationManager mLocationManager; 
//private Location mLastLocation; 
private LocationListener mLocationListener; 
public double mLatitude; 
public double mLongitude; 
private Context context; 


//constructor 
public LocationHelper(Context context) { 
    //saves the context received from activity that instantiates LocationHelper into a local variable 
    this.context = context; 
} 

public void startConnection() { 
    // Create an instance of GoogleAPIClient. 
    if (mGoogleApiClient == null) { 
     mGoogleApiClient = new GoogleApiClient.Builder(context) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 
} 

public void checkLocation(){ 
    //gets system service from LocationManager 
    mLocationManager = (LocationManager)getSystemService(LOCATION_SERVICE); 

    //checks permissions 
    if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){ 
     return; 
    } 

    mLocationListener = new LocationListener(){ 

     @Override 
     public void onLocationChanged(Location location) { 

      //checks if GPS is enabled 
      if(mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ 
       if(mLocationListener != null){ 
        if(ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){ 
         return; 
        } 
        if (mLocationManager != null) { 
         location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if(location != null){ 
          mLatitude = location.getLatitude(); 
          mLongitude = location.getLongitude(); 
          Toast.makeText(getApplicationContext(), "GPS - " + String.valueOf(mLatitude) + "," + String.valueOf(mLongitude), Toast.LENGTH_SHORT).show(); 
         } 
        } 
       } 
      } 
      //checks if internet is enabled 
      else if(mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ 
       if(mLocationManager != null){ 
        location = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if(location != null){ 
         mLatitude = location.getLatitude(); 
         mLongitude = location.getLongitude(); 
         Toast.makeText(getApplicationContext(), "NETWORK - " + String.valueOf(mLatitude) + "," + String.valueOf(mLongitude), Toast.LENGTH_SHORT).show(); 

        } 
       } 
      } 
      //method for setting location request parameters 
      setLocationRequest(); 
     } 



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

     } 

     @Override 
     public void onProviderEnabled(String provider) { 

     } 

     @Override 
     public void onProviderDisabled(String provider) { 

     } 
    }; 

} 


@Override 
public void onConnected(@Nullable Bundle bundle) { 

} 

@Override 
public void onConnectionSuspended(int i) { 

} 

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

} 

public void setLocationRequest(){ 
    //sets locationrequest parameters 
    LocationRequest mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(5000); 
    mLocationRequest.setFastestInterval(3000); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 
} 

public double getLatitudeForNote() { 
    return mLatitude; 
} 

public double getLongitudeForNote(){ 
    return mLongitude; 
} 

}

錯誤 -

E/AndroidRuntime: FATAL EXCEPTION: main 
       Process: com.example.a8460p.locationotes, PID: 1715 
       java.lang.RuntimeException: Unable to resume activity {com.example.a8460p.locationotes/com.example.a8460p.locationotes.MapsActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate() 
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3160) 
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3191) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2529) 
        at android.app.ActivityThread.access$900(ActivityThread.java:154) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:234) 
        at android.app.ActivityThread.main(ActivityThread.java:5526) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
       Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate() 
        at android.app.Activity.getSystemService(Activity.java:5300) 
        at com.example.a8460p.locationotes.LocationHelper.checkLocation(LocationHelper.java:66) 
        at com.example.a8460p.locationotes.MapsActivity.setMapMarkers(MapsActivity.java:71) 
        at com.example.a8460p.locationotes.MapsActivity.onResume(MapsActivity.java:88) 
        at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1259) 
        at android.app.Activity.performResume(Activity.java:6361) 
        at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3149) 
        at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3191)  
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2529)  
        at android.app.ActivityThread.access$900(ActivityThread.java:154)  
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1391)  
        at android.os.Handler.dispatchMessage(Handler.java:102)  
        at android.os.Looper.loop(Looper.java:234)  
        at android.app.ActivityThread.main(ActivityThread.java:5526)  
        at java.lang.reflect.Method.invoke(Native Method)  
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)  

在此先感謝您的幫助!

回答

1

步驟#1:從LocationHelper刪除extends Activity。這不是一項活動。

步驟#2:使用context撥打電話getSystemService()LocationHelper

第3步:決定是否要使用Android的LocationManagerLocationRequest從播放服務SDK,並擺脫與你不打算使用一個相關聯的所有代碼。

0

您需要在onCreate完成後初始化您的LocationHelper實例。您可以將相關的代碼移動到onMapReady()方法中。

相關問題