簡體   English   中英

android 6.0文件提供程序無法在FileProvider.getUriForFile上使用空指針

[英]android 6.0 file provider not working null pointer on FileProvider.getUriForFile

以下代碼用於嘗試為Android Nougat做准備的文件提供程序:

清單文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.securefilesharing"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="25" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera"/>
    <uses-feature android:name="android.hardware.camera.autofocus" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".HomeSecureFileShareTestActivity"
            android:label="@string/title_activity_home_secure_file_share_test" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.securefilesharing.fileprovider"
            android:enabled="false"
            android:grantUriPermissions="true" >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider_path" />
        </provider>

    </application>

</manifest>

文件提供者xml:

<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="external_files" path="/"/>
</paths>

構造URI並傳遞給相機意圖:

private Uri createImageFile() throws Exception {
         File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), System.currentTimeMillis() + ".jpg");
         //File file = new File(System.currentTimeMillis() + ".jpg");

         Uri photoUri = null;

         try{
             photoUri = FileProvider.getUriForFile(this, "com.securefilesharing.fileprovider", file);
         }
         catch(Exception e){
             Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
         }

         return photoUri;
     }

View.OnClickListener ocl = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            try {
                uri = createImageFile();
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                cameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            } catch (Exception e) {
                Log.e(TAG, TAG + ": " + e.toString());
            }           
            startActivityForResult(cameraIntent, CAMERA_REQUEST); 
        }
    };

我也做了activity.requestPermissions(forPermissions.toArray(new String [0]),PERMISSION_CODE); 對於相機,讀寫外部文件

以下是異常消息:

06-22 15:04:13.962:E / HomeSecureFileShareTestActivity(31851):HomeSecureFileShareTestActivity:java.lang.NullPointerException:嘗試調用虛擬方法'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content .pm.PackageManager,java.lang.String)'上的空對象引用

<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.securefilesharing.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true" >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_provider_path" />
        </provider>

更改清單的提供商部分...請參閱: https//developer.android.com/guide/topics/manifest/provider-element.html#enabled

嘗試這個,

private Context mContext=YourActivity.this;

private static final int REQUEST = 112;


View.OnClickListener ocl = new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        if (Build.VERSION.SDK_INT >= 23) {
            String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE,android.Manifest.permission.READ_EXTERNAL_STORAGE,android.Manifest.permission.CAMERA};
            if (!hasPermissions(mContext, PERMISSIONS)) {
                ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
            } else {
                openCamera()
            }
        } else {
            openCamera()'
        }
    }
};

獲取權限結果

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case REQUEST: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openCamera();
            } else {
                Toast.makeText(mContext, "The app was not allowed to write in your storage", Toast.LENGTH_LONG).show();
            }
        }
    }
}

檢查棉花糖的權限

private static boolean hasPermissions(Context context, String... permissions) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
        for (String permission : permissions) {
            if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
    }
    return true;
}

表現

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"/>
<uses-feature android:name="android.hardware.camera.autofocus" />

openCamera功能

public void openCamera()
{
    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    try {
        uri = createImageFile();


        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);

    } catch (Exception e) {
        Log.e(TAG, TAG + ": " + e.toString());
    }           
    startActivityForResult(cameraIntent, CAMERA_REQUEST); 
}

createImageFile函數:

 public Uri  createImageFile() {
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/TEST");
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);

    String fName = "Image_" + n + ".jpg";
    File file = new File(myDir, fName);
    if (file.exists()) {
        file.delete();
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Uri uriImage = Uri.fromFile(file);
    return uriImage;
}
File file = new File(Environment.getExternalStorageDirectory(), "/download/"+ GlobalVars.apkname+".apk");
System.out.println("file>>>>>"+file);
Uri fileUri = Uri.fromFile(file);

if (Build.VERSION.SDK_INT >= 24) {
    fileUri = FileProvider.getUriForFile(MainActivity.this,getPackageName(), file);
    System.out.println("File URI>>>>>"+fileUri);
    //fileUri = FileProvider.get
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM