Android应用在请求权限之前崩溃

时间:2016-02-18 04:44:59

标签: android permissions android-permissions

我正在尝试创建一个下载内容然后移动它的应用。

当我手动进入应用偏好设置并授予其权限时,该应用有效,但我正在尝试在应用打开时为其授予权限。

到目前为止,这是我的代码

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" />

每当我尝试打开应用程序时,它都会强行关闭。

有什么想法吗?

我在Marshmallow 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 个答案:

答案 0 :(得分:1)

方法checkSelfPermission(String)已添加到API 23.在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);
}

答案 1 :(得分: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

答案 2 :(得分:0)

试试这个..

在清单文件中的MainActivity中添加主题,如下所示  机器人:主题=&#34; @风格/ Theme.AppCompat.Light.NoActionBar&#34;

答案 3 :(得分: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清楚地说明了

  

引起:java.lang.NullPointerException:尝试调用虚方法&#39; android.view.View android.view.Window.findViewById(int)&#39;在空对象引用上

您应该采取以下方式:

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);

答案 4 :(得分:0)

我添加了以下内容:

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        //What you want to do when permissions are met
    }