当前位置: 首页 > 知识库问答 >
问题:

为什么我的Android应用程序在请求权限时崩溃?

章光华
2023-03-14

每当我请求权限时,我的应用程序就会崩溃。作为清单标记的子项,我在清单中定义了正确的使用权限。它没有给出任何错误,只是一个弹出窗口说包安装程序已经停止,监视器中有一行说“sendUserActionEvent()mView==null”,我不确定这与崩溃有关。

这是我请求权限的片段:

if(ContextCompat.checkSelfPermission(MainActivity.this, 
    Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
    Log.d("MAD", "Internet permission is not enabled!");

    requestPermissions(new String[] {Manifest.permission.INTERNET}, 
        PERMISSION_REQUEST_INTERNET);

    return null;
}

最低sdk设置为23,在三星Galaxy S7上进行测试。

你可以在这里看到完整的代码https://github.com/zimmyg/MAD_Test

Logcat在这里:

09-18 17:25:05.350 9483-9489/mad.mad_test I/art: Debugger is active
09-18 17:25:05.540 9483-9483/mad.mad_test I/System.out: Debugger has connected
09-18 17:25:05.540 9483-9483/mad.mad_test I/System.out: waiting for debugger to settle...
09-18 17:25:05.730 9483-9483/mad.mad_test I/System.out: waiting for debugger to settle...
09-18 17:25:05.930 9483-9483/mad.mad_test I/System.out: waiting for debugger to settle...
09-18 17:25:06.130 9483-9483/mad.mad_test I/System.out: waiting for debugger to settle...
09-18 17:25:06.330 9483-9483/mad.mad_test I/System.out: waiting for debugger to settle...
09-18 17:25:06.530 9483-9483/mad.mad_test I/System.out: waiting for debugger to settle...
09-18 17:25:06.740 9483-9483/mad.mad_test I/System.out: waiting for debugger to settle...
09-18 17:25:06.940 9483-9483/mad.mad_test I/System.out: waiting for debugger to settle...
09-18 17:25:07.130 9483-9483/mad.mad_test I/System.out: waiting for debugger to settle...
09-18 17:25:07.330 9483-9483/mad.mad_test I/System.out: debugger has settled (1339)
09-18 17:25:07.350 9483-9483/mad.mad_test I/InjectionManager: Inside getClassLibPath caller 
09-18 17:25:07.380 9483-9483/mad.mad_test W/System: ClassLoader referenced unknown path: /data/app/mad.mad_test-1/lib/arm64
09-18 17:25:07.500 9483-9483/mad.mad_test W/System: ClassLoader referenced unknown path: /data/app/mad.mad_test-1/lib/arm64
09-18 17:25:07.520 9483-9483/mad.mad_test D/InjectionManager: InjectionManager
09-18 17:25:07.520 9483-9483/mad.mad_test D/InjectionManager: fillFeatureStoreMap mad.mad_test
09-18 17:25:07.520 9483-9483/mad.mad_test I/InjectionManager: Constructor mad.mad_test, Feature store :{}
09-18 17:25:07.520 9483-9483/mad.mad_test I/InjectionManager: featureStore :{}
09-18 17:25:07.610 9483-9483/mad.mad_test W/ResourcesManager: getTopLevelResources: /data/app/mad.mad_test-1/base.apk / 1.0 running in mad.mad_test rsrc of package mad.mad_test
09-18 17:25:07.620 9483-9483/mad.mad_test D/ContextRelationManager: ContextRelationManager() : FEATURE_ENABLED=true
09-18 17:25:07.620 9483-9483/mad.mad_test D/RelationGraph: garbageCollect()
09-18 17:25:07.620 9483-9483/mad.mad_test W/ResourcesManager: getTopLevelResources: /data/app/mad.mad_test-1/base.apk / 1.0 running in mad.mad_test rsrc of package mad.mad_test
09-18 17:25:07.750 9483-9483/mad.mad_test W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
09-18 17:25:07.830 9483-9483/mad.mad_test D/AbsListView: Get MotionRecognitionManager
09-18 17:25:07.830 9483-9483/mad.mad_test E/MotionRecognitionManager: mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy@2d093ce
09-18 17:25:07.830 9483-9483/mad.mad_test E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@a661eda
09-18 17:25:07.830 9483-9483/mad.mad_test E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy@a661eda
09-18 17:25:07.840 9483-9483/mad.mad_test D/Activity: performCreate Call Injection manager
09-18 17:25:07.840 9483-9483/mad.mad_test I/InjectionManager: dispatchOnViewCreated > Target : mad.mad_test.MainActivity isFragment :false
09-18 17:25:07.870 9483-9483/mad.mad_test D/SecWifiDisplayUtil: Metadata value : SecSettings2
09-18 17:25:07.870 9483-9483/mad.mad_test D/ViewRootImpl: #1 mView = com.android.internal.policy.PhoneWindow$DecorView{3d6112e I.E...... R.....ID 0,0-0,0}
09-18 17:25:07.880 9483-9534/mad.mad_test D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
09-18 17:25:07.950 9483-9534/mad.mad_test D/libEGL: eglInitialize EGLDisplay = 0x7f83aff178
09-18 17:25:07.950 9483-9534/mad.mad_test I/OpenGLRenderer: Initialized EGL, version 1.4

                                                            [ 09-18 17:25:07.960  9483: 9534 D/         ]
                                                            ro.exynos.dss isEnabled: 0
09-18 17:25:07.980 9483-9534/mad.mad_test D/mali_winsys: new_window_surface returns 0x3000,  [1440x2560]-format:1
09-18 17:25:08.090 9483-9483/mad.mad_test I/InjectionManager: dispatchCreateOptionsMenu :mad.mad_test.MainActivity
09-18 17:25:08.090 9483-9483/mad.mad_test I/InjectionManager: dispatchPrepareOptionsMenu :mad.mad_test.MainActivity
09-18 17:25:08.100 9483-9483/mad.mad_test W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
09-18 17:25:08.110 9483-9534/mad.mad_test D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : mad.mad_test
09-18 17:25:08.200 9483-9483/mad.mad_test D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
09-18 17:25:08.240 9483-9483/mad.mad_test I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@92514f9 time:304111002
09-18 17:25:18.620 9483-9483/mad.mad_test D/ViewRootImpl: ViewPostImeInputStage processPointer 0
09-18 17:25:18.690 9483-9483/mad.mad_test D/ViewRootImpl: ViewPostImeInputStage processPointer 1
09-18 17:25:18.700 9483-9800/mad.mad_test D/MAD: Internet permission is not enabled!
09-18 17:25:18.830 9483-9534/mad.mad_test D/OpenGLRenderer: endAllActiveAnimators on 0x7f72b30800 (RippleDrawable) with handle 0x7f72b7d7e0
09-18 17:25:18.830 9483-9483/mad.mad_test D/ViewRootImpl: #3 mView = null

共有2个答案

濮阳旺
2023-03-14

有一些权限将在安装时自动授予,并且无法撤销。我们称之为正常权限(PROTECTION_Normal)。

所以“android.permission.INTERNET”在正常权限列表下,运行时无需询问权限。

艾璞瑜
2023-03-14

嗨,我检查了您的代码,经过几次更新后,它对我来说工作正常。您的下载网址不起作用。我还添加了如何给予多个权限。

public class MainActivity extends AppCompatActivity {
private ArrayList<String> entries;
private ArrayAdapter<String> adapter;

private ListView listView;
private Button btnStartTest;

//PERMISSIONS
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (Build.VERSION.SDK_INT >= 23) {
        // Marshmallow+
        callMultiplePermissions();
    } else {
        // Pre-Marshmallow
    }
    entries = new ArrayList<>();
    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, entries);

    listView = (ListView ) findViewById(R.id.listView);
    listView.setAdapter(adapter);

    btnStartTest = (Button) findViewById(R.id.btnStartTest);
    btnStartTest.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new BackgroundAsync().execute();
        }
    });
}

private class BackgroundAsync extends AsyncTask<Integer, Double, Long> {

    private final Integer FILE_SIZE = 5 * 1024 * 1024; // 5MB

    private String current;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        btnStartTest.setEnabled(false);
        current = new String();
    }

    @Override
    protected Long doInBackground(Integer... params) {

            try {
                URL downURL = new URL("http://api.androidhive.info/progressdialog/hive.jpg");
                URLConnection conn = downURL.openConnection();

                long startTime = System.currentTimeMillis();
                long totalDownloaded = 0;

                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                int read = 0;
                byte[] buf = new byte[1024];
                while ((read = bis.read(buf)) != -1) {
                    totalDownloaded += read;
                    // Publish percentage
                    publishProgress(((double)totalDownloaded/(double)FILE_SIZE) * 100.0);
                }

                long finishTime = System.currentTimeMillis();

                return finishTime - startTime;
            } catch (Exception e) {
                Log.e("MAD", e.getMessage());
                return null;
            }

    }

    @Override
    protected void onProgressUpdate(Double... progress) {
        // Show progress update
    }

    @Override
    protected void onPostExecute(Long result) {
        super.onPostExecute(result);

        if(result != null) {
            current = "Speed: " + ((double)FILE_SIZE / 1024 / 1024)/((double)result / 1000) + "MB/s";
            Log.e("MAD","check speed :" + current);
        }
        btnStartTest.setEnabled(true);
    }
}

//************** Multiple permissions ****************//

/**
 * Call multiple Permissions
 */

private void callMultiplePermissions() {
    List<String> permissionsNeeded = new ArrayList<String>();

    final List<String> permissionsList = new ArrayList<String>();
    if (!addPermission(permissionsList, Manifest.permission.ACCESS_NETWORK_STATE))
        permissionsNeeded.add("NETWORK STATE");
    if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
        permissionsNeeded.add("WRITE EXTERNAL STORAGE");

    if (permissionsList.size() > 0) {
        if (permissionsNeeded.size() > 0) {
            // Need Rationale
            String message = "You need to grant access to " + permissionsNeeded.get(0);
            for (int i = 1; i < permissionsNeeded.size(); i++)
                message = message + ", " + permissionsNeeded.get(i);

            if (Build.VERSION.SDK_INT >= 23) {
                // Marshmallow+
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            } else {
                // Pre-Marshmallow
            }

            return;
        }
        if (Build.VERSION.SDK_INT >= 23) {
            // Marshmallow+
            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
        } else {
            // Pre-Marshmallow
        }

        return;
    }

}

/**
 * add Permissions
 *
 * @param permissionsList
 * @param permission
 * @return
 */
private boolean addPermission(List<String> permissionsList, String permission) {
    if (Build.VERSION.SDK_INT >= 23) {
        // Marshmallow+
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (!shouldShowRequestPermissionRationale(permission))
                return false;
        }
    } else {
        // Pre-Marshmallow
    }

    return true;
}

/**
 * Permissions results
 *
 * @param requestCode
 * @param permissions
 * @param grantResults
 */
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
            Map<String, Integer> perms = new HashMap<>();
            // Initial
            perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED);
            perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
            // Fill with results
            for (int i = 0; i < permissions.length; i++)
                perms.put(permissions[i], grantResults[i]);
            // Check for ACCESS_FINE_LOCATION and others
            if (perms.get(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED
                    && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED ) {
                // All Permissions Granted

            } else {
                // Permission Denied
                Toast.makeText(MainActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
                        .show();
            }
        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
}

在清单文件中添加了这些权限

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

谢谢,希望这能帮到你。

 类似资料:
  • 我需要捕获设备的IMEI和IMSI以及您已经知道的信息,这需要一个权限。当这个对话框窗口向用户请求这个权限时,我的应用程序被停止了。怎么解决? 更新2(AndroidManifest.xml文件):

  • 我将只同意graph API中的特定管理权限。 但它请求所有租户权限。 当前逻辑为 如何请求对特定权限的同意?

  • 我试图调用ViewModel中片段中的函数,但每次调用时它都会崩溃,我不知道为什么。下面是代码: 呼吁协程: 函数的代码: 如果我不使用协同程序,只使用我收到一个错误,说我必须从其他挂起函数或协同程序调用这个函数。 这就是错误: 我的ViewModel是: 在我称之为协程的片段中,我这样声明它:

  • 我想看看我的应用程序是否可以在即时应用程序中完成。我的应用程序是基于从我的船上获取NFC发送的温度。 不幸的是,android开发者网站的常见问题表示,只有以下几个权限可用。 https://developer.android.com/topic/instant-apps/faqs.html 这意味着NFC权限是不可能的? 提前感谢您的回答

  • 我再一次需要你的帮助堆叠天花! 我一直在开发SDK,现在需要验证用户是否授予了位置或文件写入等权限。 验证是可以的,但是我想如果需要的话,我应该请求许可。问题是,我绝对不能访问任何活动。我可以使用appContext来检查权限,但是我不能像这样监听onRequest estPermissionsResult。 有没有一种聪明的方法可以向我这边请求许可,或者我应该让使用我的SDK的开发人员及时请求许