Skip to content

Instantly share code, notes, and snippets.

@ahmadmust8
Created April 7, 2017 01:14
Show Gist options
  • Save ahmadmust8/d5874a69e75b7296982ef0f0be7b701e to your computer and use it in GitHub Desktop.
Save ahmadmust8/d5874a69e75b7296982ef0f0be7b701e to your computer and use it in GitHub Desktop.
Permissions requests by dialog for Android 6.0 or later
package ahmad.mostafa.permissiondemo;
import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class PermissionDemoActivity extends AppCompatActivity {
private static String TAG = "PermissionDemo";
private static final int RECORD_REQUEST_CODE = 101;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission_demo);
// remember ! add permission to the Manifest file
// like this " <uses-permission android:name="android.permission.RECORD_AUDIO"/> "
int permission = ContextCompat.checkSelfPermission(this
, Manifest.permission.RECORD_AUDIO);
if ( permission != PackageManager.GET_PERMISSIONS )
{
Log.i(TAG, "Permission to record denied");
// show the user why we need this permission by dialog
if ( ActivityCompat.shouldShowRequestPermissionRationale(this
,Manifest.permission.RECORD_AUDIO) )
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Permission required");
builder.setMessage("Permission to access the microphone is\n" +
"required for this app to record audio.");
builder.setPositiveButton("ok" , new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id) {
Log.i(TAG, "Clicked");
makeRequest();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}else {
// check permission if
makeRequest();
}
}
}
protected void makeRequest(){
ActivityCompat.requestPermissions(this
, new String[]{Manifest.permission.RECORD_AUDIO}
, RECORD_REQUEST_CODE);
}
@Override
public void onRequestPermissionsResult(int requestCode
, @NonNull String[] permissions
, @NonNull int[] grantResults) {
switch (requestCode) {
case RECORD_REQUEST_CODE: {
if (grantResults.length == 0
|| grantResults[0] !=
PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission has been denied by user");
} else {
Log.i(TAG, "Permission has been granted by user");
}
return;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment