2015-11-25 2 views
2

Я получаю это сообщение при отладке приложения в своем приложении спидометра.К сожалению приложение остановилось во время отладки

Вот мой Java класс:

public class MainActivity extends AppCompatActivity implements LocationListener { 

    /** 
    * ATTENTION: This was auto-generated to implement the App Indexing API. 
    * See https://g.co/AppIndexing/AndroidStudio for more information. 
    */ 
    private GoogleApiClient client; 

    @TargetApi(Build.VERSION_CODES.M) 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 

     if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // public void requestPermissions(@NonNull String[] permissions, int requestCode) 
      // 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 Activity#requestPermissions for more details. 
      return; 
     } 
     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 

     this.onLocationChanged(null); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); 
    } 

    @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_main, 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_settings) { 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     TextView txt = (TextView) this.findViewById(R.id.textView); 

     if (location == null) { 
      txt.setText("-.- m/s"); 
     } else { 
      float nCurrentSpeed = location.getSpeed(); 
      txt.setText(nCurrentSpeed + "m/s"); 
     } 

    } 

    @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 onStart() { 
     super.onStart(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     client.connect(); 
     Action viewAction = Action.newAction(
       Action.TYPE_VIEW, // TODO: choose an action type. 
       "Main Page", // TODO: Define a title for the content shown. 
       // TODO: If you have web page content that matches this app activity's content, 
       // make sure this auto-generated web page URL is correct. 
       // Otherwise, set the URL to null. 
       Uri.parse("http://host/path"), 
       // TODO: Make sure this auto-generated app deep link URI is correct. 
       Uri.parse("android-app://mycompany.com.speedometer3/http/host/path") 
     ); 
     AppIndex.AppIndexApi.start(client, viewAction); 
    } 

    @Override 
    public void onStop() { 
     super.onStop(); 

     // ATTENTION: This was auto-generated to implement the App Indexing API. 
     // See https://g.co/AppIndexing/AndroidStudio for more information. 
     Action viewAction = Action.newAction(
       Action.TYPE_VIEW, // TODO: choose an action type. 
       "Main Page", // TODO: Define a title for the content shown. 
       // TODO: If you have web page content that matches this app activity's content, 
       // make sure this auto-generated web page URL is correct. 
       // Otherwise, set the URL to null. 
       Uri.parse("http://host/path"), 
       // TODO: Make sure this auto-generated app deep link URI is correct. 
       Uri.parse("android-app://mycompany.com.speedometer3/http/host/path") 
     ); 
     AppIndex.AppIndexApi.end(client, viewAction); 
     client.disconnect(); 
    } 
} 

и это мой LogCat

E/AndroidRuntime: FATAL EXCEPTION: main 
java.lang.NoSuchMethodError: mycompany.com.speedometer3.MainActivity.checkSelfPermission 
     at mycompany.com.speedometer3.MainActivity.onCreate(MainActivity.java:39) 
     at android.app.Activity.performCreate(Activity.java:5255) 
     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097) 
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2213) 
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2299) 
     at android.app.ActivityThread.access$700(ActivityThread.java:154) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1284) 
     at android.os.Handler.dispatchMessage(Handler.java:99) 
     at android.os.Looper.loop(Looper.java:137) 
     at android.app.ActivityThread.main(ActivityThread.java:5306) 
     at java.lang.reflect.Method.invokeNative(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:511) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 
     at dalvik.system.NativeStart.main(Native Method) 
+3

java.lang.NoSuchMethodError: mycompany.com .speedometer3.MainActivity.checkSelfPermission опубликуйте этот код – johnrao07

+3

'NoSuchMethodError: ... checkSelfPermission', вы, вероятно, запускаете это на устройстве до Android 6.0. Перед использованием функции необходимо выполнить проверку против 'build.version_codes.marshmallow' –

ответ

2

Вы работаете приложение на устройстве, которое старше, чем Android 6.0. checkSelfPermission() был добавлен в Android 6.0.

варианты:

  • Установка вашего проекта minSdkVersion до 23, так что он будет работать только на платформе Android 6.0+ устройств

  • Использование ContextCompat.checkSelfPermission() вместо checkSelfPermission()

  • называют только checkSelfPermission() на устройствах Android 6.0+, путем сравнения Build.VERSION.SDK_INT с Build.VERSION_CODES.M

1

Способ checkSelfPermission(String permission) не доступен на устройстве, на котором запущено приложение. Этот метод был введен с Android 6.0, и ваше устройство имеет версию ниже этого.

Вы можете исправить это следующим образом:

if (Build.VERSION.SDK_INT >= 23) { 
     if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // public void requestPermissions(@NonNull String[] permissions, int requestCode) 
     // 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 Activity#requestPermissions for more details. 
     return; 
    } 
} 

Как ваш minSdkVersion, вероятно, ниже 23, поместить его в отдельную функцию, как это:

@TargetApi(23) 
private boolean checkPermissionLocation() { 
    if (Build.VERSION.SDK_INT >= 23) { 
     if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // public void requestPermissions(@NonNull String[] permissions, int requestCode) 
      // 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 Activity#requestPermissions for more details. 
      return false; 
     } 
    } 
    return true; 
} 
Смежные вопросы