Android应用在请求权限前崩溃

4

我正在尝试制作一个应用程序,它可以下载某些东西并将其移动。

当我手动进入应用程序偏好设置并授予权限时,该应用程序可以正常工作,但是我正在尝试在应用程序打开时授予权限。

以下是我目前的代码:

package idkwhatimdoing.com.emojiupdaterroot;

import android.Manifest;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;

import java.io.IOException;
public class MainActivity extends AppCompatActivity {

    final Spinner emojiSpinner = (Spinner) findViewById(R.id.emojiSpinner);
    final String emojiSpinnerText = emojiSpinner.getSelectedItem().toString();
    final Button updateEmojiButton = (Button) findViewById(R.id.updateEmojiButton);
    // Assume thisActivity is the current activity

    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);


        updateEmojiButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
// Here, thisActivity is the current activity
                if (ContextCompat.checkSelfPermission(MainActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {

                    // Should we show an explanation?
                    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                            Manifest.permission.WRITE_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(MainActivity.this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_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_WRITE_EXTERNAL_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    ProgressDialog progress = new ProgressDialog(MainActivity.this);
                    progress.setMessage("Downloading New Emojis");
                    progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    progress.setIndeterminate(true);
                    progress.show();
                    try {
                        Runtime.getRuntime().exec("su");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                    if (emojiSpinnerText.equals("iPhone iOS 9.1")) {
                        String iosEmojiUrl = "http://idkwhatimdoing/androidapps/iPhone9_1.ttf";
                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(iosEmojiUrl));
                        request.setTitle("Downloading_New_Emojis");
                        request.setDescription("iPhone iOS 9.1");
// in order for this if to run, you must use the android 3.2 to compile your app
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                        }
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "NotoColorEmoji.ttf");

                        progress.setMessage("Updating Emojis");
// get download service and enqueue file
                        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                        manager.enqueue(request);
                    } else if (emojiSpinnerText.equals("Android Marshmallow 6.0.1")) {
                        String iosEmojiUrl = "http://idkwhatimdoing/androidapps/Android6_0_1.ttf";
                        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(iosEmojiUrl));
                        request.setTitle("Downloading_New_Emojis");
                        request.setDescription("Android Marshmallow 6.0.1");
// in order for this if to run, you must use the android 3.2 to compile your app
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                        }
                        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "NotoColorEmoji.ttf");

                        progress.setMessage("Updating Emojis");
// get download service and enqueue file
                        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                        manager.enqueue(request);
                    }

                } 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
        }
    }
}

我的清单有

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />

每当我尝试打开这个应用时,它就会强制关闭。
你有什么想法吗?
我正在Marhsmallow 6.0.1上进行测试。
以下是我的logcat。
02-18 01:27:32.586 20844-20844/idkwhatimdoing.com.emojiupdaterroot E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: idkwhatimdoing.com.emojiupdaterroot, PID: 20844
                                                                                java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{idkwhatimdoing.com.emojiupdaterroot/idkwhatimdoing.com.emojiupdaterroot.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
                                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
                                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
                                                                                    at android.app.ActivityThread.access$900(ActivityThread.java)
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java)
                                                                                    at android.os.Looper.loop(Looper.java)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
                                                                                    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:117)
                                                                                 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
                                                                                    at android.app.Activity.findViewById(Activity.java)
                                                                                    at idkwhatimdoing.com.emojiupdaterroot.MainActivity.<init>(MainActivity.java:22)
                                                                                    at java.lang.Class.newInstance(Native Method)
                                                                                    at android.app.Instrumentation.newActivity(Instrumentation.java)
                                                                                    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java) 
                                                                                    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java) 
                                                                                    at android.app.ActivityThread.access$900(ActivityThread.java) 
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java) 
                                                                                    at android.os.Handler.dispatchMessage(Handler.java) 
                                                                                    at android.os.Looper.loop(Looper.java) 
                                                                                    at android.app.ActivityThread.main(ActivityThread.java) 
                                                                                    at java.lang.reflect.Method.invoke(Native Method) 
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java) 
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java) 
                                                                                    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:117
5个回答

1

API 23 添加了 checkSelfPermission(String) 方法。在 API 23 以下版本中,此权限始终被授予,因此该方法无用。在处理权限之前,请检查 API 版本。

int permissionCheck = 0;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
 permissionCheck  = ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
}

它被称为ContextCompat是因为它会为你进行版本检查,并在旧版本上返回PackageManager.PERMISSION_GRANTED - ianhanniballake
1
我正在Marshmallow上运行,所以为什么需要检查呢? - IdkHowToCodeAtAll

0

尝试这个...

在你的MainActivity的清单文件中添加主题,像这样: android:theme="@style/Theme.AppCompat.Light.NoActionBar"


0
 if (Build.VERSION.SDK_INT >= 23) {

        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.e("testing", "Permission is granted");


        } else {


            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            Log.e("testing", "Permission is revoked");
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.e("testing", "Permission is already granted");

Grant permission in this way hope it may be help you

我正在 Marshmallow 上运行这个,那么为什么需要检查? - IdkHowToCodeAtAll
如果 (Build.VERSION.SDK_INT >= 23) { 如果 (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { Log.e("testing", "权限已授予");}尝试这个 - New Coder
我应该把它放在哪里? - IdkHowToCodeAtAll
1
如果您使用启动画面,请将该代码放在启动画面中。 - New Coder
我显然搞砸了什么。还是不起作用。 http://pastebin.com/raw/WRp9maBV - IdkHowToCodeAtAll
at exception exactly you got - New Coder

0

我不知道你是否已经发现,但问题不在于权限,而是以下代码。

final Spinner emojiSpinner = (Spinner) findViewById(R.id.emojiSpinner);
final String emojiSpinnerText = emojiSpinner.getSelectedItem().toString();
final Button updateEmojiButton = (Button) findViewById(R.id.updateEmojiButton);

你应该在onCreate()方法中分配值。Logcat清楚地说明了:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference

你应该按照以下方式做:

final Spinner emojiSpinner;
final String emojiSpinnerText;
final Button updateEmojiButton;

和 onCreate()

emojiSpinner = (Spinner) findViewById(R.id.emojiSpinner);
emojiSpinnerText = emojiSpinner.getSelectedItem().toString();
updateEmojiButton = (Button) findViewById(R.id.updateEmojiButton);

0
我添加了以下内容:
@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        //What you want to do when permissions are met
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接