Assent


Source link: https://github.com/afollestad/assent

Assent

Assent is designed to make Marshmallow's runtime permissions easier to use. Have the flexibility of request permissions and receiving results through callback interfaces.

Table of Contents

  1. Gradle Dependency
    1. Repository
    2. Dependency
  2. Basics
  3. Without AssentActivity
  4. Without AssentFragment
  5. Using PermissionResultSet
  6. Fragments
  7. Duplicate and Simultaneous Requests
    1. Duplicate Request Handling
    2. Simultaneous Request Handling
  8. AfterPermissionResult Annotation

Gradle Dependency

The Gradle dependency is available via jCenter. jCenter is the default Maven repository used by Android Studio.

Dependency

Add this to your module's build.gradle file:

dependencies {

  // ... other dependencies
  compile 'com.afollestad:assent:0.2.5' 
}

--

Basics

Note: you need to have needed permissions in your AndroidManifest.xml too, otherwise Android will always deny them, even on Marshmallow.

Activities

The first way to use this library is to have Activities which request permissions extend AssentActivity. AssentActivity will handle some dirty work internally, so all that you have to do is use the requestPermissions method:

public class MainActivity extends AssentActivity {

@Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

 if (!Assent.isPermissionGranted(Assent.WRITE_EXTERNAL_STORAGE)) {

 // The if statement checks if the permission has already been granted before

 Assent.requestPermissions(new AssentCallback() {

  @Override

  public void onPermissionResult(PermissionResultSet result) {

// Permission granted or denied

  
}

 
}
, 69, Assent.WRITE_EXTERNAL_STORAGE);

}

  
}
 
}

requestPermissions has 3 parameters: a callback, a request code, and a list of permissions. You can pass multiple permissions in your request like this:

Assent.requestPermissions(callback,

requestCode,
  Assent.WRITE_EXTERNAL_STORAGE, Assent.ACCESS_FINE_LOCATION);

Fragments

If you use Fragment's in your app, it's recommended that they extend AssentFragment. They will update Context references in Assent, and handle Fragment permission results for you. Relying on the Fragment's Activity can lead to occasional problems.

public class MainFragment extends AssentFragment {

// Use Assent the same way you would in an Activity 
}

Without AssentActivity

If you don't want to extend AssentActivity, you can use some of Assent's other methods in order to mimic the behavior:

public class MainActivity extends AppCompatActivity {

@Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Updates the activity when the Activity is first created

// That way you can request permissions from within onCreate()

Assent.setActivity(this, this);

if (!Assent.isPermissionGranted(Assent.WRITE_EXTERNAL_STORAGE)) {

 // The if statement checks if the permission has already been granted before

 Assent.requestPermissions(new AssentCallback() {

  @Override

  public void onPermissionResult(PermissionResultSet result) {

// Permission granted or denied

  
}

 
}
, 69, Assent.WRITE_EXTERNAL_STORAGE);

}

  
}

@Override
  protected void onResume() {

super.onResume();

// Updates the activity every time the Activity becomes visible again

Assent.setActivity(this, this);

  
}

@Override
  protected void onPause() {

super.onPause();

// Cleans up references of the Activity to avoid memory leaks

if (isFinishing())

 Assent.setActivity(this, null);

  
}

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

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

// Lets Assent handle permission results, and contact your callbacks

Assent.handleResult(permissions, grantResults);

  
}
 
}

Without AssentFragment

If you don't want to extend AssentFragment, you can use some of Assent's other methods in order to mimic the behavior:

public class AssentFragment extends Fragment

implements FragmentCompat.OnRequestPermissionsResultCallback {

@Override
  public void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Assent.setFragment(this, this);

  
}

@Override
  public void onResume() {

super.onResume();

Assent.setFragment(this, this);

  
}

@Override
  public void onPause() {

super.onPause();

if (getActivity() != null && getActivity().isFinishing())

 Assent.setFragment(this, null);

  
}

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

super.onRequestPermissionsResult(requestCode, permissions, grantResults);

Assent.handleResult(permissions, grantResults);

  
}
 
}

Using PermissionResultSet

PermissionResultSet is returned in callbacks. It has a few useful methods:

PermissionResultSet result = // ...  String[] permissions = result.getPermissions();
  boolean granted = result.isGranted(permissions[0]);
  Map<String, Boolean> grantedMap = result.getGrantedMap();
  boolean allGranted = result.allPermissionsGranted();

Fragments

A huge plus to using callbacks rather than relying on onRequestPermissionsResult is that you can request permission from Fragments and receive the result right in the Fragment, as long as the Activity your Fragment is in handles results.

public class MainFragment extends Fragment {

// ... view creation logic and other stuff here

 @Override
  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

super.onViewCreated(view, savedInstanceState);

if (!Assent.isPermissionGranted(Assent.WRITE_EXTERNAL_STORAGE)) {

 Assent.requestPermissions(new AssentCallback() {

  @Override

  public void onPermissionResult(PermissionResultSet result) {

// Permission granted or denied

  
}

 
}
, 69, Assent.WRITE_EXTERNAL_STORAGE);

}

  
}
 
}

Duplicate and Simultaneous Requests

Duplicate Request Handling

If you were to do this...

Assent.requestPermissions(new AssentCallback() {

  @Override
  public void onPermissionResult(PermissionResultSet result) {

// Permission granted or denied
  
}
 
}
, 69, Assent.WRITE_EXTERNAL_STORAGE);
  Assent.requestPermissions(new AssentCallback() {

  @Override
  public void onPermissionResult(PermissionResultSet result) {

// Permission granted or denied
  
}
 
}
, 69, Assent.WRITE_EXTERNAL_STORAGE);

...the permission would only be requested once, and both callbacks would be called at the same time.

An example situation where this would be useful: if you use tabs in your app, and multiple Fragments which are created at the same request the same permission, the permission dialog would only be shown once and both Fragments would be updated with the result.

Simultaneous Request Handling

If you were to do this...

Assent.requestPermissions(new AssentCallback() {

  @Override
  public void onPermissionResult(PermissionResultSet result) {

// Permission granted or denied
  
}
 
}
, 34, Assent.WRITE_EXTERNAL_STORAGE);
  Assent.requestPermissions(new AssentCallback() {

  @Override
  public void onPermissionResult(PermissionResultSet result) {

// Permission granted or denied
  
}
 
}
, 69, Assent.ACCESS_FINE_LOCATION);

...Assent would wait until the first permission request is done before executing the second request.

This is important, because if you were you request different permissions at the same time without Assent, the first permission request would be cancelled and denied and the second one would be shown immediately.


AfterPermissionResult Annotation

As a convenience, you can use the AfterPermissionResult annotation to have Assent invoke a method in any class when a specific set of permissions is granted or denied.

public class MainActivity extends AssentActivity {

@Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

// Request WRITE_EXTERNAL_STORAGE and ACCESS_FINE_LOCATION permissions, with the current class as the target

Assent.requestPermissions(MainActivity.this, 69,

  Assent.WRITE_EXTERNAL_STORAGE, Assent.ACCESS_FINE_LOCATION);

  
}

 @AfterPermissionResult(permissions = {
 Assent.WRITE_EXTERNAL_STORAGE, Assent.ACCESS_FINE_LOCATION 
}
)
  public void onPermissionResult(PermissionResultSet result) {

// Use PermissionResultSet
  
}
 
}

Behind the scenes, Assent is actually using a callback. When the callback is received, it finds the first AfterPermissionResult annotated method in the target class object (with a matching permission set) and invokes it.

The target class could be any object. It even works like this:

public class OtherClass {

@AfterPermissionResult(permissions = {
Assent.WRITE_EXTERNAL_STORAGE, Assent.ACCESS_FINE_LOCATION
}
)
  public void onPermissionResult(PermissionResultSet result) {

// Use permission result
  
}
 
}
  public class MainActivity extends AssentActivity {

private OtherClass mOther;

@Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

mOther = new OtherClass();

// Request WRITE_EXTERNAL_STORAGE and ACCESS_FINE_LOCATION permissions, with mOther as the target

Assent.requestPermissions(mOther, 69,

  Assent.WRITE_EXTERNAL_STORAGE, Assent.ACCESS_FINE_LOCATION);

  
}
 
}

LICENSE

Copyright 2016 Aidan Follestad

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Resources

RapidJSON is a JSON parser and generator for C++. It was inspired by RapidXml.

Features:

  • Small but complete. It supports both SAX and DOM style API.
  • Fast. Its performance can be comparable to strlen().
  • Self-contained. It does not depend on external libraries.
  • Memory friendly. Each JSON value occupies exactly 16/20 bytes.
  • Unicode friendly.

EdgeEffectOverride is library designed to help override the blue overscroll_edge and overscroll_glow effects used by the the EdgeEffect class.

Simply import the project into your library, replace existing references to ScrollView, ListView, ExpandableListView, GridView & ViewPager with references to the the classes found in this library.

No need to edit any graphics, simply colorize the edge effect dynamically or via the layout xml, easy!

A Reactive wrapper around Google's YouTube Data API.

material-dialogs library allows you to use a consistently Material themed dialog on all versions of Android, along with specific customizations that make it easier to brand the dialog.

Navigation Drawer Activity with material design style and simplified methods.

Every major open-source project has its own style guide: a set of conventions (sometimes arbitrary) about how to write code for that project. It is much easier to understand a large codebase when all the code in it is in a consistent style.

"Style" covers a lot of ground, from "use camelCase for variable names" to "never use global variables" to "never use exceptions." This project holds the style guidelines we use for Google code. If you are modifying a project that originated at Google, you may be pointed to this page to see the style guides that apply to that project.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes