Can't use Lollipop specific classes in Android

2019-08-27 15:48发布

问题:

I'm having problems with Lollipop specific classes in a minSdk 21 project. This is my gradle.build

android {
compileSdkVersion 21
buildToolsVersion "21.1.0"

defaultConfig {
    applicationId "com.mypackage"
    minSdkVersion 21
    targetSdkVersion 21
    versionCode 1
    versionName "1.0"
}

When I try to use UsageStatsManager I get a 'Cannot resolve symbol UsageStatsManager' error from Android Studio. Or if I use Context.JOB_SCHEDULER_SERVICE/Context.USAGE_STATS_SERVICE the constant isn't found.

This is an example class that gives me these errors.

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.app.usage.UsageStatsManager;
import android.app.job.JobScheduler;

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    UsageStatsManager mUsageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
    JobScheduler mJobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
}

In this case even the import for UsageStatsManager fails with the error 'Cannot resolve symbol UsageStatsManager', while the JobScheduler is found (but I can't use it because I have no Context.JOB_SCHEDULER_SERVICE)

I've downloaded android-21 platform from the SDK Manager, I have both the source and the SDK.

Am I missing something?

回答1:

Something from an old installation of Android Studio was causing problems, so I followed this answer and deleted the caches. It now works.



回答2:

With respect to JOB_SCHEDULER_SERVICE, that's a known issue and can be overcome temporarily via a @SuppressWarnings("ResourceType") annotation until you get your hands on a newer Android Studio.

With regards to android.app.usage.UsageStatsManager, though, I can import that fine on Android Studio 0.8.9 with compileSdkVersion 21.