Skip to content

Commit

Permalink
fragment support, javadoc updated, added new method "startApplication…
Browse files Browse the repository at this point in the history
…SettingsActivity" and refacroting
  • Loading branch information
NoNews committed Nov 5, 2017
1 parent fb28982 commit 33fb6dd
Show file tree
Hide file tree
Showing 13 changed files with 416 additions and 97 deletions.
4 changes: 2 additions & 2 deletions library/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ android {
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
versionName "1.1.1"

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

Expand Down Expand Up @@ -42,7 +42,7 @@ dependencies {
publish {
groupId = 'ru.alexbykov'
artifactId = 'nopermission'
publishVersion = '1.1.0'
publishVersion = '1.1.1'
desc = 'Permission library for Android'
licences = ['Apache-2.0']
website = 'https://github.com/NoNews/NoPermission'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;
Expand All @@ -22,8 +28,9 @@
public class PermissionHelper {


private static final int PERMISSION_REQUEST_CODE = 1005001;
private static final int PERMISSION_REQUEST_CODE = 98;
private Activity activity;
private Fragment fragment;
private String[] permissions;
private Runnable successListener;
private Runnable deniedListener;
Expand All @@ -33,9 +40,14 @@ public PermissionHelper(Activity activity) {
this.activity = activity;
}

public PermissionHelper(Fragment fragment) {
this.fragment = fragment;
}


/**
* @param permission is single permission, which you want to ask
* @return current object
*/
public PermissionHelper check(String permission) {
this.permissions = new String[1];
Expand All @@ -46,6 +58,7 @@ public PermissionHelper check(String permission) {

/**
* @param permissions is array of permissions, which you want to ask
* @return current object
*/
public PermissionHelper check(String... permissions) {
this.permissions = permissions;
Expand All @@ -57,6 +70,7 @@ public PermissionHelper check(String... permissions) {
* Setup failure callback
*
* @param listener called when user deny permission
* @return current object
*/
public PermissionHelper onSuccess(Runnable listener) {
this.successListener = listener;
Expand All @@ -67,6 +81,7 @@ public PermissionHelper onSuccess(Runnable listener) {
* Setup failure callback
*
* @param listener called when user deny permission
* @return current object
*/
public PermissionHelper onDenied(Runnable listener) {
this.deniedListener = listener;
Expand All @@ -75,9 +90,10 @@ public PermissionHelper onDenied(Runnable listener) {


/**
* Setup never ask again callback
* This method setup never ask again callback
*
* @param listener called when permission in status "never ask again"
* @return current object
*/
public PermissionHelper onNeverAskAgain(Runnable listener) {
this.neverAskAgainListener = listener;
Expand All @@ -86,18 +102,23 @@ public PermissionHelper onNeverAskAgain(Runnable listener) {


/**
* Check API-version and listeners
* This method check API-version and listeners
*
* @throws RuntimeException if isListenersCorrect return false
*/
public void run() {
if (isListenersCorrect()) {
runSuccessOrAskPermissions();
} else {
throw new RuntimeException("OnPermissionSuccessListener or OnPermissionFailureListener not installed. Please, use onSuccess and onDenied methods");
throw new RuntimeException("permissionSuccessListener or permissionDeniedListener have null reference. You must realize onSuccess and onDenied methods");
}
}


/**
* This method run successListener if all permissions granted,
* and run method checkPermissions, if needToAskPermissions return false
*/
private void runSuccessOrAskPermissions() {
if (isNeedToAskPermissions()) {
checkPermissions();
Expand All @@ -108,30 +129,43 @@ private void runSuccessOrAskPermissions() {


/**
* Request only those permissions that are not granted.
* If all are granted, the success method is triggered
* This method request only those permissions that are not granted.
* If all are granted, success callback called
*/
@RequiresApi(api = Build.VERSION_CODES.M)
private void checkPermissions() {
final String[] permissionsForRequest = getPermissionsForRequest();
if (permissionsForRequest.length > 0) {
activity.requestPermissions(permissionsForRequest, PERMISSION_REQUEST_CODE);
askPermissions(permissionsForRequest);
} else {
successListener.run();
}
}

@SuppressLint("NewApi")
private void askPermissions(String[] permissionsForRequest) {
if (activity != null) {
activity.requestPermissions(permissionsForRequest, PERMISSION_REQUEST_CODE);
} else {
fragment.requestPermissions(permissionsForRequest, PERMISSION_REQUEST_CODE);
}
}


/**
* Check listeners for null
* This method check listeners for null
*
* @return true if you realized method onSuccess and onDenied
*/
private boolean isListenersCorrect() {
return successListener != null && deniedListener != null;
}


/**
* We need to ask permission only if API >=23
* This method ckeck api version
*
* @return true if API >=23
*/
private boolean isNeedToAskPermissions() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
Expand Down Expand Up @@ -203,7 +237,11 @@ private void runNeverAskAgain() {
* @return true if permission granted and false if permission not granted
*/
private boolean isPermissionNotGranted(String permission) {
return ActivityCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED;
if (activity != null) {
return ActivityCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED;
} else {
return ActivityCompat.checkSelfPermission(fragment.getContext(), permission) != PackageManager.PERMISSION_GRANTED;
}
}


Expand All @@ -213,16 +251,40 @@ private boolean isPermissionNotGranted(String permission) {
*/
@RequiresApi(api = Build.VERSION_CODES.M)
private boolean isNeverAskAgain(String permission) {
return !activity.shouldShowRequestPermissionRationale(permission);
if (activity != null) {
return !activity.shouldShowRequestPermissionRationale(permission);
} else {
return !fragment.shouldShowRequestPermissionRationale(permission);
}
}


/**
* To avoid memory leaks, you must change reference to null
* This method start application settings activity
* Note: is not possible to open at once screen with application permissions.
*/
public void startApplicationSettingsActivity() {
final Context context = activity == null ? fragment.getContext() : activity;
final Intent intent = new Intent();
final Uri uri = Uri.fromParts("package", context.getPackageName(), null);
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(uri);
context.startActivity(intent);
}

/**
* This method change listeners reference to avoid memory leaks
*/
public void unsubscribe() {
activity = null;
deniedListener = null;
successListener = null;

if (activity != null) {
activity = null;
}
if (fragment != null) {
fragment = null;
}
if (neverAskAgainListener != null) {
neverAskAgainListener = null;
}
Expand Down
10 changes: 10 additions & 0 deletions sample/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,27 @@ android {

testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

jackOptions {
enabled true
}
}


buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:26.1.0'
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
Expand Down
21 changes: 15 additions & 6 deletions sample/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ru.alexbykov.permissionssample">
package="ru.alexbykov.permissionssample">

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_CONTACTS" />

<application
android:allowBackup="true"
Expand All @@ -13,12 +13,21 @@
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".activities.LocationSampleActivity">
<!--<intent-filter>-->
<!--<action android:name="android.intent.action.MAIN" />-->

<!--<category android:name="android.intent.category.LAUNCHER" />-->
<!--</intent-filter>-->
</activity>
<activity android:name=".MainActivity">

<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,75 +1,35 @@
package ru.alexbykov.permissionssample;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;

import ru.alexbykov.nopermission.PermissionHelper;
import ru.alexbykov.permissionssample.fragments.ChooseFragment;

public class MainActivity extends AppCompatActivity {


private final String TAG = "PermissionResult: ";
private static final int LAYOUT = R.layout.activity_main;
private PermissionHelper permissionHelper;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(LAYOUT);
setupPermissionHelper();
setupUX();
}


private void setupUX() {
findViewById(R.id.btnAskPermission).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
askLocationPermission();
}
});
startFragment(ChooseFragment.newInstance(), false);
}

private void askLocationPermission() {
permissionHelper.check(Manifest.permission.ACCESS_COARSE_LOCATION).onSuccess(new Runnable() {
@Override
public void run() {
Log.d(TAG, "LocationSuccess");
((TextView) findViewById(R.id.tvResult)).setText(R.string.result_success);
}
}).onDenied(new Runnable() {
@Override
public void run() {
Log.d(TAG, "LocationDenied");
((TextView) findViewById(R.id.tvResult)).setText(R.string.result_failure);
}
}).onNeverAskAgain(new Runnable() {
@Override
public void run() {
Log.d(TAG, "LocationNeverAskAgain");
((TextView) findViewById(R.id.tvResult)).setText(R.string.result_never_ask_again);
}
}).run();

}
public void startFragment(Fragment fragment, boolean addToBackStack) {

private void setupPermissionHelper() {
permissionHelper = new PermissionHelper(this);
FragmentTransaction transaction =
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.lt_container, fragment);
if (addToBackStack) {
transaction.addToBackStack(fragment.getTag());
}
transaction.commit();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
permissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

@Override
protected void onDestroy() {
permissionHelper.unsubscribe();
super.onDestroy();
}
}
Loading

0 comments on commit 33fb6dd

Please sign in to comment.