代码在Android 4.4上运行,但在android 6.0.1上运行

时间:2016-04-05 09:27:13

标签: android permissions gallery

当我运行以下代码时,它会在Android版本4.4上运行,但它不能在Android版本6.0.1上运行。在这个版本上我得到一个空白屏幕。我已经完成了类似的问题,但我的问题仍然存在。请帮帮我。谢谢。

public class MainActivity extends AppCompatActivity {
private static final String TAG = "Error" ;
private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
ArrayList<String> f = new ArrayList<String>();
File[] listFile;
private ArrayList<File> fileList = new ArrayList<File>();


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    showGalleryPreview();
    GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
    imageAdapter = new ImageAdapter();
    imagegrid.setAdapter(imageAdapter);


  }


     private void showGalleryPreview() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_STORAGE);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_STORAGE: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                getFromSdcard();

                // permission was granted, yay! Do the
                // contacts-related task you need to do.

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}


public void getFromSdcard()
{

    File file=  new File(Environment.getExternalStorageDirectory()
            .getAbsolutePath());
    getfile(file);



 }


public ArrayList<File> getfile(File dir) {
    File listFile[] = dir.listFiles();
    if (listFile != null && listFile.length > 0) {
        for (int i = 0; i < listFile.length; i++) {
            if (listFile[i].isDirectory()) {
                fileList.add(listFile[i]);
                getfile(listFile[i]);

            } else {
                if (listFile[i].getName().endsWith(".png")
                        || listFile[i].getName().endsWith(".jpg")
                        || listFile[i].getName().endsWith(".jpeg")
                        || listFile[i].getName().endsWith(".gif"))

                {
                    fileList.add(listFile[i]);
                }
            }

        }
    }
    return fileList;
}

public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;

    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return fileList.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(
                    R.layout.galleryitem, null);
            holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);

            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }


        Bitmap myBitmap = BitmapFactory.decodeFile(String.valueOf(fileList.get(position)));
        holder.imageview.setImageBitmap(myBitmap);
        return convertView;
    }
}
class ViewHolder {
    ImageView imageview;

    }}

这是清单文件

    <?xml version="1.0" encoding="utf-8"?>
   <manifest   xmlns:android="http://schemas.android.com/apk/res/android"
package="r.image">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

这是gradle文件

     apply plugin: 'com.android.application'

    android {
compileSdkVersion 23
buildToolsVersion "23.0.2"

defaultConfig {
    applicationId "r.image"
    minSdkVersion 17
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
  }

 dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
}

3 个答案:

答案 0 :(得分:1)

访问存储时,您很可能会忘记request permissions at runtime。从Marshmallow开始,仅仅在Manifest中声明你需要的权限是不够的。

答案 1 :(得分:1)

从Android 6.0(API级别23)开始,用户在应用程序运行时向应用程序授予权限,而不是在安装应用程序时。在调用它之前,您必须首先询问存储权限:

getFromSdcard();

您可以在此处阅读有关如何申请权限的信息: http://developer.android.com/training/permissions/requesting.html

答案 2 :(得分:0)

所有关于Android M的新运行时权限。请看一下这篇文章http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en