我正在编写应该在Android L和M上运行的应用程序。
正如您可能知道的那样,对于Android M,需要在代码中询问权限,以便从外部存储(sdcard)中读取或读取,如下所示:
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==
PackageManager.PERMISSION_GRANTED)
requestPermissions(new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
但是,我遇到了一个问题,因为调用checkSelfPermission
需要API级别23(而不是22,因为我需要Lollipop支持)。
我尝试添加@TargetApi(Build.VERSION_CODES.MNC)
,但我遇到了另一个问题 - "Cannot resolved symbol MNC"
所以问题是,对于Lollipop和Marshmallow,如何编写代码来保存sdcard中的文件?
编辑:项目结构设置:
编译Sdk版本:API 23:Android 5.X(MNC
Min Sdk版本:API 22:Android 5.1(Lollipop)
目标Sdk版本:API 23:Android 5.X(MNC)
谢谢
答案 0 :(得分:7)
将编译版本更改为API 23(MARSHMALLOW) 并添加依赖
dependencies {
...
compile 'com.android.support:appcompat-v7:23.1.1'
...
}
并为只有棉花糖的条件
if (Build.VERSION.SDK_INT > 22) {
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)==
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;
}
}
这是因为checkselfpermission方法仅适用于marsmallow
答案 1 :(得分:1)
您需要使用ActivityCompat
派生的ContextCompat
。checkSelfPermission
定义dependencies {
...
compile 'com.android.support:appcompat-v7:23.1.1'
...
}
public class YourActivity extends ActivityCompat {
...
public void onStart() {
...
checkSelfPermission(...);
...
}
...
}
。您需要在gradle构建中包含Android支持库才能使用此类。
private RestAdapter buildRestAdapter(String baseUrl, Context ctx) {
RestAdapter.LogLevel logLevel = RestAdapter.LogLevel.FULL;
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setLogLevel(logLevel);
if (!TextUtils.isEmpty(baseUrl))
builder.setEndpoint(baseUrl);
builder.setRequestInterceptor(new RequestInterceptor() {
@Override
public void intercept(RequestFacade request) {
int maxStale = 60 * 60 * 24 * 28;
request.addHeader("Cache-Control",
"public, only-if-cached, max-stale=" + maxStale);
}
});
File httpCacheDirectory = new File(ctx.getCacheDir(), "responses");
Cache cache = new Cache(httpCacheDirectory, 10 * 1024 * 1024);
OkHttpClient okHttpClient = new OkHttpClient();
if (cache != null) {
okHttpClient.setCache(cache);
}
builder.setClient(new OkClient(okHttpClient));
return builder.build();
}