Android Splash运行时权限不起作用

时间:2019-02-20 06:12:34

标签: android android-permissions runtime-permissions

我使用了与仓库相同的代码:

https://github.com/pcess/tutorials/tree/master/SplashPermissions

回购中的独立应用程序运行正常。但是,当在我的应用程序中实现相同的代码时,权限会陷入循环,并且该应用程序不会授予任何权限。

清单文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.******.dms_IN"
android:versionCode="6"
android:versionName="5.7.0">

<supports-screens
    android:anyDensity="true"
    android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true" />

<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
package="com.******.dms_IN"
android:versionCode="6"
android:versionName="5.7.0">


<application
   android:name="com.******.screen.MyApp"
   android:allowBackup="false"
   android:icon="@mipmap/icon_new"
   android:label="@string/ApplicationName"
   android:largeHeap="true"
   android:theme="@style/MyCustomTheme">
   <activity
       android:name="com.******.screen.SplashPermissionsActivity"
       android:label="@string/ApplicationName">
   </activity>
   <activity android:name="com.******.screen.FirstTimePermission"
       android:label="@string/ApplicationName"
       android:screenOrientation="portrait">
       <intent-filter>
           <action android:name="android.intent.action.MAIN" />

           <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
   </activity>
   <activity
       android:name="com.******.screen.StartActivity"
       android:label="@string/ApplicationName"
       android:screenOrientation="portrait">
       </activity>
   <activity
       android:name="com.******.screen.ColgateDMSWelcome"
       android:label="@string/ApplicationName"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.Setup"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.MyGridView"
       android:screenOrientation="portrait"
       android:windowSoftInputMode="adjustPan" />
   <activity
       android:name="com.******.screen.ProdOrderBooking"
       android:screenOrientation="portrait"
       android:windowSoftInputMode="adjustPan" />
   <activity
       android:name="com.******.screen.OrderBookingSummary"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.OrderBookingView"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.OrderSummary"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.OrderBookingKPI"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.SKUWiseSummary"
       android:screenOrientation="portrait"
       android:windowSoftInputMode="stateAlwaysHidden" />
   <activity
       android:name="com.******.screen.BTWrapperActivity"
       android:screenOrientation="portrait"
       android:theme="@android:style/Theme" />
   <activity
       android:name="com.******.screen.CallSheetSummary"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.MSSStore"
       android:screenOrientation="portrait"
       android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />
   <activity
       android:name="com.******.screen.SalesmanKPI"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.Salesman_KPI_Re"
       android:screenOrientation="portrait"
       android:theme="@android:style/Theme.NoTitleBar.Fullscreen" />
   <activity
       android:name="com.******.screen.CustomerSummary"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.SchemeList"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.CashCollection"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.RouteList"
       android:screenOrientation="portrait"
       android:theme="@android:style/Theme.Dialog" />
   <activity
       android:name="com.******.screen.ListAsDialog"
       android:screenOrientation="portrait"
       android:theme="@android:style/Theme.Dialog" />
   <activity
       android:name="com.******.map.Map"
       android:screenOrientation="portrait"
       android:theme="@android:style/Theme.Dialog" />
   <activity
       android:name="com.******.screen.NotificationView"
       android:screenOrientation="portrait"
       android:theme="@android:style/Theme.Dialog" />
   <activity
       android:name="com.******.signature.CaptureSignature"
       android:screenOrientation="portrait" />
   <activity
       android:name="com.******.screen.ImageViewer"
       android:screenOrientation="portrait" /> <!-- [START firebase_service] -->
   <service android:name="com.******.PushNotify.MyFirebaseMessagingService">
       <intent-filter>
           <action android:name="com.google.firebase.MESSAGING_EVENT" />
       </intent-filter>
   </service> <!-- [END firebase_service] -->
   <!-- [START firebase_iid_service] -->
   <service
       android:name="com.******.PushNotify.MyFirebaseInstanceIDService"
       android:exported="true">
       <intent-filter>
           <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
       </intent-filter>
   </service>

   <activity android:name="com.******.screen.CreateCustomer" />
 </application>

 </manifest>

代码:

FirstTimePermission活动:

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;

public class FirstTimePermission extends Activity {

/*
 * ---------------------------------------------
 *
 * Private Fields
 *
 * ---------------------------------------------
 */
/**
 * The time that the splash screen will be on the screen in milliseconds.
 */
private int                 timeoutMillis       = 5000;

/** The time when this {@link Activity} was created. */
private long                startTimeMillis     = 0;

/** The code used when requesting permissions */
private static final int    PERMISSIONS_REQUEST = 1234;

/** A random number generator for the background colors. */
private static final Random random              = new Random();

/**
 * The TextView which is used to inform the user whether the permissions are
 * granted.
 */
private TextView textView            = null;
private static final int    textViewID          = View.generateViewId();

/*
 * ---------------------------------------------
 *
 * Getters
 *
 * ---------------------------------------------
 */
/**
 * Get the time (in milliseconds) that the splash screen will be on the
 * screen before starting the {@link Activity} who's class is returned by
 * {@link #getNextActivityClass()}.
 */
public int getTimeoutMillis() {
    return timeoutMillis;
}

/** Get the {@link Activity} to start when the splash screen times out. */
@SuppressWarnings("rawtypes")
public Class getNextActivityClass() {
    return StartActivity.class;
}

/**
 * Get the list of required permissions by searching the manifest. If you
 * don't think the default behavior is working, then you could try
 * overriding this function to return something like:
 *
 * <pre>
 * <code>
 * return new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
 * </code>
 * </pre>
 */
public String[] getRequiredPermissions() {
    String[] permissions = null;
    try {
        permissions = getPackageManager().getPackageInfo(getPackageName(),
                PackageManager.GET_PERMISSIONS).requestedPermissions;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    if (permissions == null) {
        return new String[0];
    } else {
        return permissions.clone();
    }
}

/*
 * ---------------------------------------------
 *
 * Activity Methods
 *
 * ---------------------------------------------
 */
@TargetApi(23)
@Override
protected void onCreate(Bundle savedInstanceState) {

    /** Default creation code. */
    super.onCreate(savedInstanceState);

    /** Create the layout that will hold the TextView. */
    LinearLayout mainLayout = new LinearLayout(this);
    mainLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

    /** Add a TextView and set the initial text. */
    textView = new TextView(this);
    textView.setTextSize(50);
    textView.setId(textViewID);
    textView.setText("Waiting for permissions...");
    mainLayout.addView(textView, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

    /** Set the background color. */
    int off = 128;
    int rest = 256 - off;
    int color = Color.argb(255, off + random.nextInt(rest), off + random.nextInt(rest), off + random.nextInt(rest));
    mainLayout.setBackgroundColor(color);

    /** Set the mainLayout as the content view */
    setContentView(mainLayout);

    /**
     * Save the start time of this Activity, which will be used to determine
     * when the splash screen should timeout.
     */
    startTimeMillis = System.currentTimeMillis();

    /**
     * On a post-Android 6.0 devices, check if the required permissions have
     * been granted.
     */
    if (Build.VERSION.SDK_INT >= 23) {
        checkPermissions();
    } else {
        startNextActivity();
    }
}

/**
 * See if we now have all of the required dangerous permissions. Otherwise,
 * tell the user that they cannot continue without granting the permissions,
 * and then request the permissions again.
 */
@TargetApi(23)
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if (requestCode == PERMISSIONS_REQUEST) {
        checkPermissions();
    }
}

/*
 * ---------------------------------------------
 *
 * Other Methods
 *
 * ---------------------------------------------
 */
/**
 * After the timeout, start the {@link Activity} as specified by
 * {@link #getNextActivityClass()}, and remove the splash screen from the
 * backstack. Also, we can change the message shown to the user to tell them
 * we now have the requisite permissions.
 */
private void startNextActivity() {
    runOnUiThread(() -> textView.setText("Permissions granted..."));
    long delayMillis = getTimeoutMillis() - (System.currentTimeMillis() - startTimeMillis);
    if (delayMillis < 0) {
        delayMillis = 0;
    }
    new Handler().postDelayed(() -> {
        startActivity(new Intent(FirstTimePermission.this, getNextActivityClass()));
        finish();
    }, delayMillis);
}

/**
 * Check if the required permissions have been granted, and
 * {@link #startNextActivity()} if they have. Otherwise
 * {@link #requestPermissions(String[], int)}.
 */
private void checkPermissions() {
    String[] ungrantedPermissions = requiredPermissionsStillNeeded();
    if (ungrantedPermissions.length == 0) {
        startNextActivity();
    } else {
        requestPermissions(ungrantedPermissions, PERMISSIONS_REQUEST);
    }
}

/**
 * Convert the array of required permissions to a {@link Set} to remove
 * redundant elements. Then remove already granted permissions, and return
 * an array of ungranted permissions.
 */
@TargetApi(23)
private String[] requiredPermissionsStillNeeded() {

    Set<String> permissions = new HashSet<String>();
    for (String permission : getRequiredPermissions()) {
        permissions.add(permission);
    }
    for (Iterator<String> i = permissions.iterator(); i.hasNext();) {
        String permission = i.next();
        if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
            Log.d(SplashPermissionsActivity.class.getSimpleName(),
                    "Permission: " + permission + " already granted.");
            i.remove();
        } else {
            Log.d(SplashPermissionsActivity.class.getSimpleName(),
                    "Permission: " + permission + " not yet granted.");
        }
    }
    return permissions.toArray(new String[permissions.size()]);
}

成绩(应用程序):

apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.******.dms_IN"
    minSdkVersion 24
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
buildTypes {
    release {
        minifyEnabled false
        shrinkResources false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
}

}

dependencies {
implementation files('libs/BixolonPrinter.jar')
implementation files('libs/commons-codec.jar')
implementation files('libs/mpandroidchartlibrary-2-1-3.jar')
implementation files('libs/sc-light-jdk15on-1.47.0.2.jar')
implementation files('libs/android-sm_https_v2_IN.jar')
implementation 'androidx.legacy:legacy-support-v4:1.0.0-beta01'
implementation 'com.google.code.gson:gson:2.8.0'
implementation 'com.google.guava:guava:18.0'
implementation 'com.google.firebase:firebase-messaging:11.8.0'
implementation 'me.leolin:ShortcutBadger:1.1.16@aar'
implementation 'net.zetetic:android-database-sqlcipher:3.5.9@aar'
implementation('com.crashlytics.sdk.android:crashlytics:2.7.1@aar') {
    transitive = true
}
implementation 'com.google.firebase:firebase-config:11.8.0'
implementation 'com.google.firebase:firebase-core:11.8.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
}
apply plugin: 'com.google.gms.google-services'

1 个答案:

答案 0 :(得分:0)

您没有正确执行运行时权限。您的代码无法运行Android 6及更高版本。跟随这个       https://github.com/ArunaMahaGamage/Android-Runtime-Permission

您打算在Play商店上发布您的应用。仔细检查通话和短信权限。如果您不需要这些权限,请将其从清单中删除。