请求运行时权限导致崩溃

Requesting Runtime Permissions Causes Crash

我 post 来这里的主要原因是我目前没有可以 运行 模拟器的计算机,我不得不将 APK 发送到我的 phone 测试一下。即使我的 phone 连接到我的电脑,或者我有第三方模拟器 运行ning,它也不会工作。由于这个...我没有错误日志。

该应用程序是一个简单的密码管理器,到目前为止所有其他功能都可以使用。我试图添加一个导出功能,但我无法真正写任何东西。我已经在线检查了其他问题和各种资源,但我似乎无法弄清楚是什么原因造成的。当调用该方法时,据我所知它什么也没做。如果我遗漏了什么,或者是否确实存在与同一问题有关的另一个问题,我深表歉意。我找不到任何遗漏的东西。

这是我正在使用的方法;

编辑: 代码已更新以反映请求 运行时间权限的更好方法,这是建议的 这最终是修复的问题应用程序。

   //Method017: Exports the account info to a .txt file.
    public void exportData() throws IOException {

        //Opens dialog to request permission.
        ActivityCompat.requestPermissions(Main.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }

    //Method to handle result of permission request.
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    //Attempt to write a file to the Download folder.
                    String content = "hello world";
                    File file;
                    FileOutputStream outputStream;
                    try {
                        file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyCache");

                        outputStream = new FileOutputStream(file);
                        outputStream.write(content.getBytes());
                        outputStream.close();

                        //According to an online source, this is necessary to make the file viewable on the device.
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        intent.setData(Uri.fromFile(file));
                        sendBroadcast(intent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(Main.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }

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

还有我的清单:

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.brand.psync">

    <application

        android:allowBackup="true"
        android:icon="@drawable/psynclogo"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:screenOrientation="portrait">
        <activity android:name=".Main">
            <intent-filter>
                <action
                    android:name="android.intent.action.MAIN"
                    android:screenOrientation="portrait"    />
                <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
                <category
                    android:name="android.intent.category.LAUNCHER"
                    android:screenOrientation="portrait" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

抱歉缺少错误日志...但如果有的话,我可能就不需要 post 了。

我试过你的代码,它工作正常。

public class SaveFileSampleActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        TextView lblBackground = new TextView(this);
        lblBackground.setBackgroundColor(Color.WHITE);
        setContentView(lblBackground);

        ActivityCompat.requestPermissions(SaveFileSampleActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
    }


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

                    //Attempt to write a file to the Download folder.
                    String content = "hello world";
                    File file;
                    FileOutputStream outputStream;
                    try {
                        file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "MyCache");

                        outputStream = new FileOutputStream(file);
                        outputStream.write(content.getBytes());
                        outputStream.close();

                        //According to an online source, this is necessary to make the file viewable on the device.
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        intent.setData(Uri.fromFile(file));
                        sendBroadcast(intent);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(SaveFileSampleActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }
}

主要内容

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".SaveFileSampleActivity"
        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>

它的工作和结果:

您可以查看您的代码。希望对您有所帮助!