Runtime Permissions Dialog box not showing up in Android 9 and below - android

The permission dialog does not show up on Android 9 and below. My code works fine on Android 11. i've tried ActivityCompat.requestPermissions() and ActivityResultLauncher but none of them work.
When it runs the line permissionResultLauncher.launch() my app crashes and it also crashes the emulator, such that i have to delete the Emulator and reinstall a new one, otherwise it won't show me anything on the screen.
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
...
</application>
public class MainActivity extends AppCompatActivity{
private ActivityMainBinding binding;
private long pressedTime;
private ActivityResultLauncher<String[]> permissionResultLauncher;
private boolean isRecordPermGranted = false;
private boolean isWritePermGranted = false;
private int totalCount;
private DBHelper dbHelper;
private ImageButton imgbtnRecord, imgbtnList;
private ImageView ivRestore;
private TextView tvLoading, tvRecord;
private boolean asyncTaskRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
totalCount = prefs.getInt("counter", 0);
if(totalCount < 4){
totalCount++;
editor.putInt("counter", totalCount);
editor.commit();
}
dbHelper = new DBHelper(this);
asyncTaskRunning = false;
imgbtnRecord = (ImageButton) findViewById(R.id.imgbtnRecord);
imgbtnList = (ImageButton) findViewById(R.id.imgbtnList);
tvLoading = findViewById(R.id.tvLoading);
tvRecord = findViewById(R.id.tvRecord);
ivRestore = findViewById(R.id.ivRestore);
tvLoading.setVisibility(View.GONE);
ivRestore.setVisibility(View.GONE);
imgbtnRecord.setVisibility(View.VISIBLE);
imgbtnList.setVisibility(View.VISIBLE);
tvRecord.setVisibility(View.VISIBLE);
isRecordPermGranted = ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
isWritePermGranted = ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
permissionResultLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
#Override
public void onActivityResult(Map<String, Boolean> result) {
if(result.get(Manifest.permission.RECORD_AUDIO)!= null){
isRecordPermGranted = result.get(Manifest.permission.RECORD_AUDIO);
Log.d("3","-------------------------" + isRecordPermGranted);
}
if(result.get(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= null){
isWritePermGranted = result.get(Manifest.permission.WRITE_EXTERNAL_STORAGE);
Log.d("4","-------------------------" + isWritePermGranted);
}
if(isWritePermGranted == false || isRecordPermGranted == false){
if(totalCount <3){
finishAffinity();
}else{
Intent intent = new Intent( MainActivity.this, PermissionActivity.class);
startActivity(intent);
}
}
}
});
imgbtnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isRecordPermGranted == false){
requestPermission();
}else{
openRecordingActivity();
}
}
});
imgbtnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isRecordPermGranted || !isWritePermGranted){
requestPermission();
}else{
openRecordingsListActivity();
}
}
});
}
public void openRecordingsListActivity() {
Intent intent = new Intent(this, RecordingsListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
public void openRecordingActivity(){
Intent intent = new Intent(this, RecordingActivity.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
if(pressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}else{
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
}
pressedTime = System.currentTimeMillis();
}
public void requestPermission(){
List<String> permissionRequests = new ArrayList<>();
if(!isRecordPermGranted && !isWritePermGranted){
permissionRequests.add(Manifest.permission.RECORD_AUDIO);
permissionRequests.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}else if(!isRecordPermGranted){
permissionRequests.add(Manifest.permission.RECORD_AUDIO);
}else if(!isWritePermGranted){
permissionRequests.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
Log.d("permissionRequests list", permissionRequests.toString());
if(!permissionRequests.isEmpty()){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
boolean shouldShowRationale = false;
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ){
shouldShowRationale = true;
Log.d("1","-------------------------");
}
if( ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)){
shouldShowRationale = true;
Log.d("2","-------------------------");
}
if(shouldShowRationale){
Toast.makeText(this, "Permissions Needed!", Toast.LENGTH_SHORT).show();
Log.d("5","-------------------------");
}else{
permissionResultLauncher.launch(permissionRequests.toArray(new String[0]));
Log.d("6","-------------------------");
}
}else{
Log.d("old permission ", permissionRequests.toArray(new String[permissionRequests.size()])+" " );
ActivityCompat.requestPermissions(MainActivity.this,permissionRequests.toArray(new String[permissionRequests.size()]), 5);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 5){
for (int i =0; i< permissions.length; i++){
if(permissions[i].equals(Manifest.permission.RECORD_AUDIO) && grantResults[i] != PackageManager.PERMISSION_GRANTED){
isRecordPermGranted = false;
}
if(permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[i] != PackageManager.PERMISSION_GRANTED){
isWritePermGranted = false;
}
}
}
if(isWritePermGranted == false || isRecordPermGranted == false){
Log.d("REQUEST PERMISSIONS RESULT", "onPermissionResult");
if(totalCount <3){
finishAffinity();
}else{
Intent intent = new Intent( MainActivity.this, PermissionActivity.class);
startActivity(intent);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
When i use the statement if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO )
then it runs the first part of the "OR" statement and shows one of the permission dialog but it never shows both, even with an "&&" or my current code in the requestPermission()
i've tried it without shouldShowRequestPermissionRationale, but it still doesn't work.
I've also added the permissions in the AndroidManifest file.

Related

Closing the "All files access" dialog when user allows access to all files in android

Presently, in my application, when the user is asked to provide "Access all files" permission, the dialog opens and remains on screen even when the user has allowed permission. Below provided screenshot shows the dialog I am referring to:-
I would like to add something in my code, which closes this dialog and opens target activity screen as soon as the user enables the toggle of "Allow access to all files".
GrantPermissionsActivity :-
public class GrantPermissionsActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
MaterialButton cancelMaterialButton, grantMaterialButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grant_permissions);
findViews();
initViews();
}
private void findViews() {
cancelMaterialButton = findViewById(R.id.materialButtonCancel);
grantMaterialButton = findViewById(R.id.materialButtonGrant);
}
private void initViews() {
if (checkPermission()){
Intent intent = new Intent(GrantPermissionsActivity.this,PasswordActivity.class);
}
cancelMaterialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(GrantPermissionsActivity.this, "Need to give permission!", Toast.LENGTH_SHORT).show();
finish();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
grantMaterialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkPermission()) {
Toast.makeText(GrantPermissionsActivity.this, "Permission already granted", Toast.LENGTH_SHORT).show();
} else if (!checkPermission()) {
requestPermission();
}
}
});
}
private boolean checkPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
return Environment.isExternalStorageManager();
} else {
int result = ContextCompat.checkSelfPermission(GrantPermissionsActivity.this, READ_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(GrantPermissionsActivity.this, WRITE_EXTERNAL_STORAGE);
return result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED;
}
}
private void requestPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
startActivityForResult(intent, 2296);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2296);
}
} else {
//below android 11
ActivityCompat.requestPermissions(GrantPermissionsActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// perform action when allow permission success
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Allow permission for storage access!", Toast.LENGTH_SHORT).show();
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
Log.d(TAG, "onActivityResult: Reachedinresult");
if (requestCode == 2296 && resultCode == RESULT_OK) {
Log.d(TAG, "onActivityResult: Reached request code");
if (SDK_INT >= Build.VERSION_CODES.R) {
Log.d(TAG, "onActivityResult: Reached SDKINT");
if (Environment.isExternalStorageManager()) {
// perform action when allow permission success
/*Intent intent = new Intent(GrantPermissionsActivity.this,PasswordActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);*/
Log.d(TAG, "onActivityResult: Reached");
} else {
checkPermission();
Toast.makeText(this, "Permission not granted", Toast.LENGTH_SHORT).show();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Please let me know the changes in the above code.
Also, check the below sample for reference:-
Replace the method requestPermission() to
private void requestPermission() {
if (SDK_INT >= Build.VERSION_CODES.R) {
try {
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
startActivityForResult(intent, 2296);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2296);
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if(Environment.isExternalStorageManager()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// perform action when allow permission success in android 11
}
});
this.cancel();
}
}
},2000,1000);
}
} else {
//below android 11
ActivityCompat.requestPermissions(GrantPermissionsActivity.this, new String[]{WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}}
If you want to start an activity from there, add flag Intent.FLAG_ACTIVITY_NEW_TASK in the Intent object, otherwise it may not work.

Splashscreen with runtime permissions

I have a splash screen on launching my app. So when showing the splash screen run time permission should show. I got this code below from github. But runtime permissions are not showing. Splash screen works fine, but runtime permission is not working when add this code below. I have added permissions read sms, read external storage, access location. I have given all these permissions in the manifest file also.
public class SplashActivity extends AppCompatActivity {
String loginstatus;
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}, 3000);
/* Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(4*1000);
startActivity(new Intent(SplashScreen.this,HomeActivity.class));
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();*/
}
private void permissioncheck() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
permissionsNeeded.add("READ");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsNeeded.add("COURLOC");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("FINELOC");
if (!addPermission(permissionsList, Manifest.permission.READ_SMS))
permissionsNeeded.add("SMS");
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);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
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;
}else
{
// Toast.makeText(this,"Permission",Toast.LENGTH_LONG).show();
LaunchApp();
}
//insertDummyContact();
}
private boolean addPermission(List<String> permissionsList, String permission) {
Boolean cond;
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;
cond = false;
}
// return true;
cond = true;
} else {
// Pre-Marshmallow
cond = true;
}
return cond;
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(SplashActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == 23) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Permission Needed To Run The App", Toast.LENGTH_LONG).show();
}
}
if (requestCode == REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_SMS, PackageManager.PERMISSION_GRANTED);
//Toast.makeText(SplashScreen.this, " Permissions are jddddd", Toast.LENGTH_SHORT).show();
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
// insertDummyContact();
//Toast.makeText(SplashScreen.this, " Permissions are l", Toast.LENGTH_SHORT).show();
LaunchApp();
} else {
// Permission Denied
Toast.makeText(SplashActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
finish();
}
}, 3000);
}
}
}
public void LaunchApp()
{
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(4*1000);
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
}
}
You need to call permissioncheck() on onCreate() method after setContentView(). Replace the code provided below with your onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
permissioncheck();
}
I removed Handler codes on onCreate() method. Instead, use onRequestPermissionResult() and start LoginActivity from it. Replace the following code to your onRequestPermissionResult().
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == 23) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Permission Needed To Run The App", Toast.LENGTH_LONG).show();
}
}
if (requestCode == REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_SMS, PackageManager.PERMISSION_GRANTED);
//Toast.makeText(SplashScreen.this, " Permissions are jddddd", Toast.LENGTH_SHORT).show();
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
// Here start the activity
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}, 3000);
} else {
// Permission Denied
Toast.makeText(SplashActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
finish();
}
}
}
Please carefully read comments in the code provided above.
Best Code
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public class Firstclass extends AppCompatActivity {
private int timeoutMillis = 5000;
/** The time when this {#link AppCompatActivity} was created. */
private long startTimeMillis = 0;
/** The code used when requesting permissions */
private static final int PERMISSIONS_REQUEST = 1234;
public int getTimeoutMillis() {
return timeoutMillis;
}
#SuppressWarnings("rawtypes")
public Class getNextActivityClass() {
return SecondActivity.class;
};
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();
}
}
#TargetApi(23)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startTimeMillis = System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= 23) {
checkPermissions();
} else {
startNextActivity();
}
}
#TargetApi(23)
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST) {
checkPermissions();
}
}
private void startNextActivity() {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
long delayMillis = getTimeoutMillis() - (System.currentTimeMillis() - startTimeMillis);
if (delayMillis < 0) {
delayMillis = 0;
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Firstclass.this, getNextActivityClass()));
finish();
}
}, delayMillis);
}
private void checkPermissions() {
String[] ungrantedPermissions = requiredPermissionsStillNeeded();
if (ungrantedPermissions.length == 0) {
startNextActivity();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(ungrantedPermissions, PERMISSIONS_REQUEST);
}
}
}
#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(Firstclass.class.getSimpleName(),
"Permission: " + permission + " already granted.");
i.remove();
} else {
Log.d(Firstclass.class.getSimpleName(),
"Permission: " + permission + " not yet granted.");
}
}
return permissions.toArray(new String[permissions.size()]);
}
}
Manifest xml permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />

OnBackPress() - Activity is blank using ZBarScannerView

I have implemented Barcode Scanner functionality in my application using ZBarScannerView.
I have an activity which contains multiple fragments and on one fragment I have a scan button. By clicking on that button I jump to scan activity where I have implemented the ZBarScannerView code.
When I got the barcode from scan activity I jumped it back to that fragment which contains the barcode click button. And then if I press back from that fragment it shows blank screen. What should I do?
Please Reply
Code for ScanActivity:
public class ScanActivity extends AppCompatActivity implements ZBarScannerView.ResultHandler {
private ZBarScannerView mScannerView;
private static final int REQUEST_CAMERA = 1;
ArrayList<ModelProductDetail> modelProductArticleCodeList;
DatabaseHelper databaseHelper;
String article_code;
ArrayList<ModelUnrecognisedCode> modelUnrecognisedCodeArrayList;
ArrayList<ModelUnrecognisedCode> singleUnrecognisedCheck;
//camera permission is needed.
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
databaseHelper = new DatabaseHelper(this);
checkUserPermission();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mScannerView == null) {
mScannerView = new ZBarScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView);
}
} else {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
checkUserPermission();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void checkUserPermission() {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, 1);
return;
}
}
loadImage();
}
private void loadImage() {
if (mScannerView == null) {
mScannerView = new ZBarScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView);
}
}
#Override
public void onResume() {
super.onResume();
if (mScannerView instanceof ZBarScannerView) {
mScannerView.startCamera();
mScannerView.setResultHandler(this);
// Stop camera on pause
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mScannerView instanceof ZBarScannerView) {
mScannerView.stopCamera(); // Stop camera on pause
}
}
#Override
public void handleResult(me.dm7.barcodescanner.zbar.Result result) {
String resultCode = result.getContents();
Log.e("TAG", "handleResult: " + resultCode);
mScannerView.stopCamera();
modelProductArticleCodeList = new ArrayList<>();
modelProductArticleCodeList = databaseHelper.getProductByArtCode(resultCode);
if (modelProductArticleCodeList.size() == 0) {
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(getApplicationContext().VIBRATOR_SERVICE);
vibrator.vibrate(1000);
singleUnrecognisedCheck = new ArrayList<>();
singleUnrecognisedCheck = databaseHelper.getUnrecognisedByCode(resultCode);
if (singleUnrecognisedCheck.size() == 0) {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("unrecognised_alert", true);
in.putExtra("unrecognised_code", resultCode);
in.putExtra("jump", "1");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Toast.makeText(this, "not matched code", Toast.LENGTH_SHORT).show();
} else {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("jump", "3");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
Toast.makeText(this, "Unrecognised code has already been added.", Toast.LENGTH_SHORT).show();
}
} else {
// for (ModelProductDetail modelProductDetail : modelProductArticleCodeList) {
// article_code = modelProductDetail.getArticle_code();
// }
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("product_art", resultCode);
in.putExtra("source_type", "art");
in.putExtra("jump", "2");
in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finishAffinity();
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
}
public void changeFragments(Fragment fragment) {
FragmentTransaction transaction = this.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
private void getDialog() {
final Dialog d = new Dialog(this);
d.setContentView(R.layout.dialog_unrecognised_code);
d.setCanceledOnTouchOutside(true);
d.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
final EditText etCode = (EditText) d.findViewById(R.id.etCode);
final EditText etrecognisedComment = (EditText) d.findViewById(R.id.etrecognisedComment);
ImageView imgClose = (ImageView) d.findViewById(R.id.imgClose);
ImageButton ibSubmit = (ImageButton) d.findViewById(R.id.ibSubmit);
imgClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
d.dismiss();
}
});
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ModelUnrecognisedCode modelUnrecognisedCode = new ModelUnrecognisedCode();
modelUnrecognisedCode.setUnrecognised_code(etCode.getText().toString());
modelUnrecognisedCode.setUnrecognised_comment(etrecognisedComment.getText().toString());
databaseHelper.addUnrecognisedCode(modelUnrecognisedCode);
// changeFragments(new SearchProductFragment());
modelUnrecognisedCodeArrayList = new ArrayList<>();
modelUnrecognisedCodeArrayList = databaseHelper.getUnrecognisedCode();
Log.e("TAG", "unrecognised code: " + modelUnrecognisedCodeArrayList.size());
d.dismiss();
}
});
d.show();
}
}
I'm assuming After successful barcode scanning you're fetching product data and if data found then you are changing the screen . So change your else statement with this and see if it works
else {
Intent in = new Intent(this, ContainAllFragmentsActivity.class);
in.putExtra("product_art", resultCode);
in.putExtra("source_type", "art");
in.putExtra("jump", "2");
startActivity(in);
finish();
}

When first open camera I don't have permissions

I have problem with access to camera first time. I installed
my app. Next go to scan to QR Code. I use to scan QR Code google vision. App show dialog, which show about the permissions, next click "Allow",but camera doesn't open. But I go back activity and go to activity which scan QR Code, camera open.
my AdnroidManifest.xml
my class
public class ScanQrCodeActivity extends AppCompatActivity {
protected void attachBaseContext(Context context) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(context));
}
private static final String TAG = "Barcode-reader";
// intent request code to handle updating play services if needed.
private static final int RC_HANDLE_GMS = 9001;
// permission request codes need to be < 256
private static final int RC_HANDLE_CAMERA_PERM = 2;
private DatabaseHandler helper;
private TextView title_app;
private CameraSource mCameraSource;
private CameraSourcePreview mPreview;
private GraphicOverlay<BarcodeGraphic> mGraphicOverlay;
String passwordString, eightChars, barcodeString, decodedBarcodeValue, OTP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qr_code);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
title_app = (TextView) findViewById(R.id.toolbar_title);
helper = new DatabaseHandler(this);
mPreview = (CameraSourcePreview) findViewById(R.id.preview);
mGraphicOverlay = (GraphicOverlay<BarcodeGraphic>) findViewById(R.id.graphicOverlay);
eightChars = getIntent().getStringExtra("eightChars");
passwordString = getIntent().getStringExtra("passwordString");
int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (rc == PackageManager.PERMISSION_GRANTED) {
createCameraSource();
} else {
requestCameraPermission();
}
Snackbar snackbar = Snackbar.make(mGraphicOverlay, R.string.zeskanuj_wygenerowany_kod, Snackbar.LENGTH_INDEFINITE);
View mView = snackbar.getView();
TextView mTextView = (TextView) mView.findViewById(android.support.design.R.id.snackbar_text);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
mTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
else
mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
snackbar.show();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.stage2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void requestCameraPermission() {
Log.w(TAG, "Camera permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
return;
}
final Activity thisActivity = this;
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
RC_HANDLE_CAMERA_PERM);
}
};
findViewById(R.id.topLayout).setOnClickListener(listener);
Snackbar.make(mGraphicOverlay, "Aby móc wykryć Qr Koda potrzebny jest dostęp do kamery.",
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, listener)
.show();
}
#SuppressLint("InlinedApi")
private void createCameraSource() {
boolean autoFocus = false;
boolean useFlash = false;
Context context = getApplicationContext();
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay);
barcodeDetector.setProcessor(
new MultiProcessor.Builder<>(barcodeFactory).build());
barcodeFactory.setNewBarcodeListener(new BarcodeTrackerFactory.OnNewBarcodeListener() {
#Override
public void onNewItem(final Barcode item) {
Log.d("BarcodeFound", "Found new barcode! " + item.rawValue);
title_app.post(new Runnable() {
#Override
public void run() {
if (!barcodeDetector.isOperational())
{
IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;
if (hasLowStorage) {
Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show();
Log.w(TAG, getString(R.string.low_storage_error));
}
}
CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1600, 1024)
.setRequestedFps(15.0f);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
builder = builder.setFocusMode(
autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null);
}
mCameraSource = builder
.setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null)
.
build();
}
#Override
protected void onResume() {
super.onResume();
startCameraSource();
}
#Override
protected void onPause() {
super.onPause();
if (mPreview != null) {
mPreview.stop();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mPreview != null) {
mPreview.release();
}
}
private void startCameraSource() throws SecurityException {
// check that the device has play services available.
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg =
GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
}
In your code immplement the following method
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 0:
boolean isPerpermissionForAllGranted = false;
if (grantResults.length > 0 && permissions.length==grantResults.length) {
for (int i = 0; i < permissions.length; i++){
if (grantResults[i] == PackageManager.PERMISSION_GRANTED){
isPerpermissionForAllGranted=true;
}else{
isPerpermissionForAllGranted=false;
}
}
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
isPerpermissionForAllGranted=true;
Log.e("value", "Permission Denied, You cannot use local drive .");
}
if(isPerpermissionForAllGranted){
// Fire here again for camera
createCameraSource();
}
break;
}
}
So what happens is When you fire the dialog for permission, you can implement the result method to come to know whether you were granted permission or not. So here you can check if the permission is granted for your permission request, You can again fire your method to open the camera.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkPermission()
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_CALENDAR)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write calendar permission is necessary to write event!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
References :
https://developer.android.com/training/permissions/requesting.html
https://www.sitepoint.com/requesting-runtime-permissions-in-android-m-and-n/
http://www.theappguruz.com/blog/runtime-permissions-in-android-marshmallow

Make telephone call on a button click in android

I have implemented a telephonic service in my app their is a button when we click on that button it will make a call but the problem is it not supporting all devices on some devices it is working well and in some devices it is not working now provide me any solution what to do so that it work on all devices.
here is my code.
public class SOSCallHelp extends AppCompatActivity {
private Button call1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_soscall_help);
call1=(Button)findViewById(R.id.call1);
call1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9078784565"));
if (ActivityCompat.checkSelfPermission(SOSCallHelp.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)
{
return;
}
startActivity(callIntent);
}
});
Please make sure you add the below permission in your App Manifest for Pre-Lollipop devices.
<uses-permission android:name="android.permission.CALL_PHONE" />
Request Permission
<uses-permission android:name="android.permission.CALL_PHONE" />
For Calling
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9078784565"));
if (ActivityCompat.checkSelfPermission(SOSCallHelp.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)
{
return;
}
startActivity(callIntent);
try this:
final int PERMISSION_REQUEST_CODE = 111;
if (driverMobile != null) {
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (!checkCallPhonePermission() || !checkReadStatePermission()) {
requestPermission();
} else {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + 1234567899));
startActivity(callIntent);
}
} else {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + + 1234567899));
startActivity(callIntent);
}
} else {
}
//permission
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE},
PERMISSION_REQUEST_CODE);
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.CALL_PHONE, Manifest.permission.READ_PHONE_STATE},
PERMISSION_REQUEST_CODES);
}
private boolean checkCallPhonePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkReadStatePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String
permissions[], int[] grantResults) {
switch (requestCode)
{
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + 123456789
startActivity(callIntent);
}
break;
}
}
Please change to this -
public class SOSCallHelp extends AppCompatActivity {
private Button call1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_soscall_help);
call1 = (Button) findViewById(R.id.call1);
call1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9078784565"));
if (ActivityCompat.checkSelfPermission(SOSCallHelp.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)
{
return;
}
PackageManager packageManager = getActivity().getPackageManager();
if (callIntent.resolveActivity(packageManager) != null) {
startActivity(callIntent);
} else {
Log.d("SOSCallHelp", "No Intent available to handle this action");
}
}
});
}
}
Simply use :
private static int REQUEST_CALL_PHONE = 111;
private void requestCallPhonePermission() {
String callPermission = android.Manifest.permission.CALL_PHONE;
int hasPermission = ContextCompat.checkSelfPermission(SOSCallHelp.this, callPermission);
String[] permissions = new String[]{callPermission};
if (hasPermission != PackageManager.PERMISSION_GRANTED) {
requestPermissions(permissions, REQUEST_CALL_PHONE);
} else {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:9078784565"));
startActivity(intent);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CALL_PHONE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:9078784565"));
startActivity(intent);
} else {
Toast.makeText(SOSCallHelp.this, "CALL_PHONE DENIED", Toast.LENGTH_SHORT).show();
}
}
}
Now call this requestCallPhonePermission() function on button click
In manifest file add <uses-permission android:name="android.permission.CALL_PHONE" />
permission.

Categories

Resources