问题在于,设置为SharedPreferences的默认值会根据我是从Google Play商店安装应用程序还是直接安装apk(或从Play商店安装后清除应用程序的存储空间)而变化。
从Play商店安装时,我得到的布尔值为false。
清除存储并再次运行,我将布尔值设为true。
private void setShowStoragePermission(boolean permission){
SharedPreferences sharedPreferences = getSharedPreferences("storagePermission", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("permission", permission).apply();
}
private boolean getShowStoragePermission(){
SharedPreferences sharedPreferences = getSharedPreferences("storagePermission", MODE_PRIVATE);
return sharedPreferences.getBoolean("permission", true);
}
在第一次干净运行时,没有保存的SharedPreferences,因此由返回的值 getShowStoragePermission()返回true。但是,从Play商店进行安装时,在前几秒钟的吐司中我看到了错误消息(“ savedPermission:false”);
您可以在应用程序的 Beta版本上自行查看: Link to app on Play store //
我正在Android P DP4上测试该应用程序。这个问题有解决方案吗?
MainActivity中的代码:
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
setToast("savedPermission: " + getShowStoragePermission(), Toast.LENGTH_LONG);
//on first run from Google Play store @getShowStoragePermission returns false - need to return true
if(getShowStoragePermission()) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
} else {
makeBingWallRequest(false);
}
}else{
//storage permission granted manually from app settings or from dialog request
createImageDir();
makeBingWallRequest(true);
}
设置了SharedPreferences的位置
private void makeBingWallRequest(boolean storagePermission){
if(getDeviceInternetStatus(context) == null && getBingWallDay() == 0){
bingImage.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.bearcats));
return;
}
if(!storagePermission){
new BingWallpaper(MainActivity.this).execute(false);
}else {
Calendar now = Calendar.getInstance(TimeZone.getDefault());
int day = now.get(Calendar.DAY_OF_MONTH);
//on first run
setToast("savedBingWallDay: " + getBingWallDay(), Toast.LENGTH_LONG);
if(getBingWallDay() == FIRST_RUN_BING_IMAGE){
saveBingWallDay();
new BingWallpaper(MainActivity.this).execute(true);
//every other run
}else if (day != getBingWallDay()) {
//if current time is past 3AM then make new request
int hourIn24 = now.get(Calendar.HOUR_OF_DAY);
if(hourIn24 >= BING_IMAGE_RESET_HOUR_IN_24){
saveBingWallDay();
new BingWallpaper(MainActivity.this).execute(true);
}else loadBitmap();
} else loadBitmap();
}
}
答案 0 :(得分:2)
我有类似的症状,后来才发现它是自动备份功能(Android 6引入)。卸载并不会清除该数据,因为这些数据是从Google的云(仅是您的Google云端硬盘)中获取的。
了解更多:https://developer.android.com/guide/topics/data/autobackup
要进行测试,只需禁用备份功能,然后重复测试以确保获得了预期的默认值。将android:allowBackup
设置为false
:
<manifest ... >
...
<application android:allowBackup="false" ... >
...
</application>
</manifest>
此外,我不得不敦促您不要将许可权状态存储在本地磁盘上。为什么不在运行时调用Context.checkCallingOrSelfPermission()
?这是更安全的方法。