2017-07-15 32 views
0

我正在学习Android谷歌地图。我已经设计了应用程序,它在kitkat中工作正常,但是当我想在棉花糖中运行相同的应用程序它崩溃。我试图解决它,但我没有得到任何结果来解决这个问题。谷歌地图奇巧(API 19)它的工作很好,但在棉花糖(API 23)它崩溃Android

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, 
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

private GoogleMap mMap; 
String location; 
GoogleApiClient apiClient; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if (googleServicesAvailable()) { 
     Toast.makeText(this, "Perfect", Toast.LENGTH_SHORT).show(); 
     setContentView(R.layout.activity_main); 
     initMap(); 
    } else { 
     //No Google Map Layout 
    } 

} 

// Obtain the SupportMapFragment and get notified when the map is ready to be used. 
private void initMap() { 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
      .findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
} 

public boolean googleServicesAvailable() { 
    GoogleApiAvailability api = GoogleApiAvailability.getInstance(); 
    int isAvailable = api.isGooglePlayServicesAvailable(this); 

    if (isAvailable == ConnectionResult.SUCCESS) { 
     return true; 
    } else if (api.isUserResolvableError(isAvailable)) { 
     Dialog dialog = api.getErrorDialog(this, isAvailable, 0); 
     dialog.show(); 
    } else { 
     Toast.makeText(this, "Cant connect to play services", Toast.LENGTH_SHORT).show(); 
    } 
    return true; 
} 


@Override 
public void onMapReady(GoogleMap googleMap) { 
    mMap = googleMap; 
    // goToLocationZoom(12.9090502,77.6241984,10); 
    // Add a marker in Sydney and move the camera 
    // LatLng ll = new LatLng(12.912128, 77.623557); 

    // CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(ll); 
    //mMap.moveCamera(cameraUpdate); 
    // mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f)); 

    // mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); 
    // mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); 


    apiClient = new GoogleApiClient.Builder(this) 
      .addApi(LocationServices.API) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .build(); 
    apiClient.connect(); 

} 

public void goToLocation(double lat, double lng) { 
    LatLng ll = new LatLng(lat, lng); 
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(ll); 
    mMap.moveCamera(cameraUpdate); 
} 

public void goToLocationZoom(double lat, double lng, float zoom) { 
    LatLng ll = new LatLng(lat, lng); 
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(ll, zoom); 
    mMap.moveCamera(cameraUpdate); 

} 

Marker marker; 

public void geolocation(View view) throws IOException { 
    EditText editText = (EditText) findViewById(R.id.editText); 

    location = editText.getText().toString(); 

    Geocoder gc = new Geocoder(this); 
    List<Address> list = gc.getFromLocationName(location, 1); 
    Address address = list.get(0); 
    String locality = address.getLocality(); 

    Toast.makeText(this, locality, Toast.LENGTH_SHORT).show(); 

    double lat = address.getLatitude(); 
    double lng = address.getLongitude(); 

    goToLocationZoom(lat, lng, 20); 

    setMarker(locality, lat, lng); 

} 

private void setMarker(String locality, double lat, double lng) { 
    if(marker!=null){ 
     marker.remove(); 
    } 

    MarkerOptions options = new MarkerOptions() 
      .title(locality) 
      // .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)) 
      .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_car)) 
      .position(new LatLng(lat,lng)) 
      .snippet("I am here"); 

    marker = mMap.addMarker(options); 
} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_none) { 
     mMap.setMapType(GoogleMap.MAP_TYPE_NONE); 
     return true; 
    } 

    if (id == R.id.action_normal) { 
     mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); 
     return true; 
    } 

    if (id == R.id.action_terrain) { 
     mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); 
     return true; 
    } 

    if (id == R.id.action_satellite) { 
     mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE); 
     return true; 
    } 

    if (id == R.id.action_hybrid) { 
     mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID); 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

LocationRequest mLocationRequest; 

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    mLocationRequest = LocationRequest.create(); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    mLocationRequest.setInterval(1000); 



    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 
    } 
    LocationServices.FusedLocationApi.requestLocationUpdates(apiClient, mLocationRequest, this); 

} 

@Override 
public void onConnectionSuspended(int i) { 

} 

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

} 

@Override 
public void onLocationChanged(Location location) { 
    if(location == null){ 
     Toast.makeText(this, "Cant get current location", Toast.LENGTH_SHORT).show(); 
    }else{ 
     LatLng ll = new LatLng(location.getLatitude(),location.getLongitude()); 
     CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll,15); 
     mMap.animateCamera(update); 
    } 

} 

}

这里我的XML代码

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" 
> 

<EditText 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/editText" 

    /> 

<Button 
    android:id="@+id/geolocation" 
    android:text="click" 
    android:onClick="geolocation" 
    android:layout_width="match_parent" 
    android:layout_height="40dp" /> 


<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:map="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/map" 
    android:layout_margin="10dp" 
    android:name="com.google.android.gms.maps.SupportMapFragment" 
    android:layout_width="match_parent" 
    android:layout_height="360dp" 
    tools:context="ab.googlemaplinear.MainActivity" /> 


<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Hello World!" 
    app:layout_constraintBottom_toBottomOf="parent" 
    app:layout_constraintLeft_toLeftOf="parent" 
    app:layout_constraintRight_toRightOf="parent" 
    app:layout_constraintTop_toTopOf="parent" /> 

这里我menifest.xml

<?xml version="1.0" encoding="utf-8"?> 

<!-- 
    The ACCESS_COARSE/FINE_LOCATION permissions are not required to use 
    Google Maps Android API v2, but you must specify either coarse or fine 
    location permissions for the 'MyLocation' functionality. 
--> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 

<!-- EXTERNAL_STORAGE permissions are optional for Android 6.0 onwards. --> 


<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:roundIcon="@mipmap/ic_launcher_round" 
    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <!-- 
     The API key for Google Maps-based APIs is defined as a string resource. 
     (See the file "res/values/google_maps_api.xml"). 
     Note that the API key is linked to the encryption key used to sign the APK. 
     You need a different API key for each encryption key, including the release key that is used to 
     sign the APK for publishing. 
     You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    --> 
    <meta-data 
     android:name="com.google.android.geo.API_KEY" 
     android:value="@string/google_maps_key" /> 

    <activity 
     android:name=".MapsActivity" 
     android:label="@string/title_activity_maps"></activity> 
</application> 

logcat的

07-15 16:46:00.922 21241-21241/abinfosoft.googlemaplinear E/AndroidRuntime: 
FATAL EXCEPTION: main 
                     Process: abinfosoft.googlemaplinear, PID: 21241 
                     java.lang.IllegalStateException: Could not execute method for android:onClick 
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) 
                      at android.view.View.performClick(View.java:5265) 
                      at android.view.View$PerformClick.run(View.java:21534) 
                      at android.os.Handler.handleCallback(Handler.java:815) 
                      at android.os.Handler.dispatchMessage(Handler.java:104) 
                      at android.os.Looper.loop(Looper.java:207) 
                      at android.app.ActivityThread.main(ActivityThread.java:5728) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
                     Caused by: java.lang.reflect.InvocationTargetException 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                      at android.view.View.performClick(View.java:5265)  
                      at android.view.View$PerformClick.run(View.java:21534)  
                      at android.os.Handler.handleCallback(Handler.java:815)  
                      at android.os.Handler.dispatchMessage(Handler.java:104)  
                      at android.os.Looper.loop(Looper.java:207)  
                      at android.app.ActivityThread.main(ActivityThread.java:5728)  
                      at java.lang.reflect.Method.invoke(Native Method)  
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)  
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)  
                     Caused by: java.io.IOException: Service not Available 
                      at android.location.Geocoder.getFromLocationName(Geocoder.java:178) 
                      at abinfosoft.googlemaplinear.MainActivity.geolocation(MainActivity.java:132) 
                      at java.lang.reflect.Method.invoke(Native Method)  
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)  
                      at android.view.View.performClick(View.java:5265)  
                      at android.view.View$PerformClick.run(View.java:21534)  
                      at android.os.Handler.handleCallback(Handler.java:815)  
                      at android.os.Handler.dispatchMessage(Handler.java:104)  
                      at android.os.Looper.loop(Looper.java:207)  
                      at android.app.ActivityThread.main(ActivityThread.java:5728)  
                      at java.lang.reflect.Method.invoke(Native Method)  
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)  
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)  

07-15 16:46:01.180 13453-16118 /? E/Auth:[GoogleAccountDataServiceImpl] getToken() - > BAD_AUTHENTICATION。帐号:,应用:com.google.android.gms,服务:的oauth2:https://www.googleapis.com/auth/contextcontroller EDW:不可用万岁凭证。 (:com.google.android.gms:0) at edx.a(:com.google.android.gms:17) at eck.a(:com.google.android.gms:51) ):fig.a(:com.google.android.gms:7) at fig.a(:com.google.android.gms:3) at fhh.a(:com.google.android.gms: 1) at fhf.a(:com.google.android.gms:17) at fhf.a(:com.google.android.gms:5) at bvd.a(:com.google.android.gms :192) at dvd.a(:com.google.android.gms:67) at dzh.a(:com.google.android.gms:5) at dzg.a(:com.google.android。 gms:1) at dzg.e(:com.google.android.gms:5) at dzg.d(:com.google.android.gms:0) at dze.b(:com.google.android.gms:0) 在lbv.a(:com.google.android.gms:0) 在lam.a(:com.google.android.gms:2) 在clb.a(:com.google.android.gms:58) (:com.google.android.gms:1) at:cgd.handleMessage(:com.google.android.gms:2) at:lgr.run(:com.google.android.gms:5) ) 在lhb.run(:com.google.android.gms:24) 在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run( ThreadPoolExe (:。com.google.android.gms:0) at java.lang.Thread.run(Thread.java:818) 07-15 16:46:01.217 13453- 16118 /? E/ctxmgr:[BaseServerTask]服务器任务(FetchAclSet)得到错误状态码= -1。 com.android.volley.VolleyError:无法获得身份验证令牌 - 是设备在线? (:com.google.android.gms:66) at cbf.run(:com.google.android.gms:1) at cgd.handleMessage(:com.google.android.gms:2) ) 在lgr.run(:com.google.android.gms:5) 在lhb.run(:com.google.android。gm:24) at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:588) at lmc.run(:com .google.android.gms:0)

+0

使用LogCat检查与您的崩溃相关的Java堆栈跟踪:https://stackoverflow.com/questions/23353173/uncomfort-myapp-has-stopped-how-can-i-solve-this – CommonsWare

+0

'我试图解决它......你在做什么来解决它?我会在每个地图方法中添加断点,并快速找出死亡的地方。这可能是版本/弃用错误,或其他。 –

+0

等待我更新我的宣言@TimBiegeleisen –

回答

0

您是否尝试访问位置的运行时权限?

相关问题