java.lang.NoClassDefFoundError在另一个项目中导入My aar时

时间:2018-11-19 01:28:05

标签: java android noclassdeffounderror aar

将模块创建为Android lib并将此类放在Java文件中

public class configuration {


    private Activity context;

    public configuration(Activity activity) {

        this.context = activity;
    }


    @SuppressLint("MissingPermission")
    public boolean checkFirstLanched() {

        SharedPreferences prefs = context.getApplicationContext().getSharedPreferences(context.getString(R.string.monitoringPref), MODE_PRIVATE);

        if (!prefs.contains("isFirst")) {
            prefs.edit().putBoolean("isFirst", false).apply();
            writeLocation();


            return true;
        }

        return false;
    }


    private boolean checkSelfPermission(String permission) {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }

    @SuppressLint("MissingPermission")
    private void writeLocation() {

        if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) && checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION)) {
            LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

            LocationListener locationListener = new LocationListener() {
                public void onLocationChanged(Location location) {
                    Log.e("location", location.getLatitude() + "");
                }

                public void onStatusChanged(String provider, int status, Bundle extras) {
                    Log.e("onStatusChanged", provider);
                }

                public void onProviderEnabled(String provider) {
                    Log.e("onProviderEnabled", provider);
                }

                public void onProviderDisabled(String provider) {
                    Log.e("onProviderDisabled", provider);
                    checkDeviceLocationIsOn();
                }
            };

            assert locationManager != null;
            locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, locationListener, null);
        }

    }


    public void checkDeviceLocationIsOn() {
        System.out.println("Test running setting request");
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                .addLocationRequest(locationRequest);
        builder.setAlwaysShow(true); //this is the key ingredient

        Task<LocationSettingsResponse> result =
                LocationServices.getSettingsClient(context).checkLocationSettings(builder.build());
        result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
            @Override
            public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
                try {
                    LocationSettingsResponse response = task.getResult(ApiException.class);
                    // All location settings are satisfied. The client can initialize location
                    // requests here.
                    // All location settings are satisfied.
                    Log.e("Location", "All location settings are satisfied. The client can initialize location");
                    writeLocation();

                } catch (ApiException exception) {
                    switch (exception.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            // Location settings are not satisfied. But could be fixed by showing the
                            // user a dialog.
                            try {
                                // Cast to a resolvable exception.
                                ResolvableApiException resolvable = (ResolvableApiException) exception;
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                resolvable.startResolutionForResult(context, 100);
                            } catch (IntentSender.SendIntentException | ClassCastException e) {
                                e.printStackTrace();
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            // Location settings are not satisfied. However, we have no way to fix the
                            // settings so we won't show the dialog.
                            Log.e("Location", "SETTINGS_CHANGE_UNAVAILABLE");
                            break;
                    }
                }
            }
        });
    }




}

我将这个实现添加到libs gradle文件中

implementation 'com.google.android.gms:play-services-location:16.0.0'

完整的gradle文件

apply plugin: 'com.android.library'

android {
    compileSdkVersion 27
    publishNonDefault true

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            pseudoLocalesEnabled false

        }
    }

}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support:support-v4:27.1.1'
    implementation 'com.android.support:support-media-compat:27.1.1'
    implementation 'com.google.android.gms:play-services-location:16.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

我想在另一个项目中测试我的库 所以我将其导出为aar发布文件,并将其导入另一个项目

所以当我在新项目中运行此代码时 像这样

public class MainActivity extends AppCompatActivity {

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

        configuration coni = new configuration(this);

        coni.checkFirstLanched();


    }
}

在关闭位置GPS时会给我这个错误,并且必须去显示对话框以请求将其打开

我的库中的configuration.java类中的这一行发生错误

    LocationRequest locationRequest = LocationRequest.create();

,此完整错误显示在logcat中

  

java.lang.NoClassDefFoundError:无法解决以下问题:   Lcom / google / android / gms / location / LocationRequest;           在com.test.monitoringtool.configuration.checkDeviceLocationIsOn(configuration.java:107)           在com.test.monitoringtool.configuration $ 1.onProviderDisabled(configuration.java:94)           在android.location.LocationManager $ ListenerTransport._handleMessage(LocationManager.java:369)           在android.location.LocationManager $ ListenerTransport.-wrap0(未知   来源:0)           在android.location.LocationManager $ ListenerTransport $ 1.handleMessage(LocationManager.java:236)           在android.os.Handler.dispatchMessage(Handler.java:108)           在android.os.Looper.loop(Looper.java:166)           在android.app.ActivityThread.main(ActivityThread.java:7425)           在java.lang.reflect.Method.invoke(本机方法)           在com.android.internal.os.Zygote $ MethodAndArgsCaller.run(Zygote.java:245)           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

有人能告诉我为什么在另一个项目中将我的lib用作aar文件时会发生此错误吗?

1 个答案:

答案 0 :(得分:0)

删除该@SuppressLint("MissingPermission"),然后修复代码。

NoClassDefFoundError来自于不在类路径中的类……这暗示着它没有被打包到AAR中-或AAR没有被打包已正确导入。您可能必须将其添加到根项目的build.gradle中,以启用AAR爆炸:

repositories {
    ...
    flatDir {
        dirs "libs"
    }
}

除非添加此内容,否则您只能从此处导入JAR

依赖项名称仅需后缀@aar

api ("com.acme:somelibrary:1.0.0@aar") {
    // transitive = true
}