Check permissions and reload the activity
Solution 1
Thanks so much guys now I can understand this, well i paste my new functional code, maybe can help to others.
public class LoadActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load);
insertDummyContactWrapper();
}
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
private void insertDummyContactWrapper() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.INTERNET))
permissionsNeeded.add("Internet.");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_NETWORK_STATE))
permissionsNeeded.add("Internet Status.");
if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
permissionsNeeded.add("Read Files.");
if (!addPermission(permissionsList, Manifest.permission.WRITE_EXTERNAL_STORAGE))
permissionsNeeded.add("Write Files.");
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 >= Build.VERSION_CODES.M) {
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
}
}
});
return;
}
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}
}
startApp();
}
private boolean addPermission(List<String> permissionsList, String permission) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
return false;
}
}
return true;
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(LoadActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
{
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.INTERNET, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
// 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.INTERNET) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_NETWORK_STATE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
startApp();
} else {
// Permission Denied
Toast.makeText(LoadActivity.this, "Some Permission is Denied, please allow permission for that the app can work.", Toast.LENGTH_SHORT)
.show();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void startApp(){
Intent intent = new Intent(this, MainActivity.class);
startActivityForResult(intent, 0);
}
}
Hope it can help to others :D
For make it i based in articles commented by other users and finally from this article
and recommend this video for noobs how me in android marshmallow
https://www.youtube.com/watch?v=C8lUdPVSzDk
Regards!
Solution 2
You check if the permission is granted then call setText else do nothing.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(checkAndRequestPermissions(this)) { //Var created
Internetstatus = (TextView) findViewById(R.id.statusInternet);
if (!verificaConexion(this)) {
Internetstatus.setText("NOT CONNECTED");
} else {
Internetstatus.setText("CONNECTED");
}
}
}
If you want to setText after permission was granted then you should override method onRequestPermissionResult and call setText from this again. The activity onCreate method would not be called again after permission was granted.
Thats the point why it works when you close and reopen the app, because the new opening of your app calls activity onCreate again and now your method checkAndRequestPermissions returns true => setText will be called
Solution 3
Read this page: https://developer.android.com/training/permissions/requesting.html
The major problem is you request permissions and then return false
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
So this if statement will not pass
if(checkAndRequestPermissions(this))
You must implement onRequestPermissionsResult() as has been said on comments.
Also, your method is private and not static so you don't need to pass Context
as an argument, you can call this
inside it like you do, just pointing not very important.
Solution 4
By implementing the interface ActivityCompat.OnRequestPermissionsResultCallback we can check whether the user is given permission to the request. If given we can load the activity once again by implementing method called onRequestPermissionsResult. For more details check this link https://developer.android.com/training/permissions/requesting.html
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isStoragePermissionGranted()) {
// code to implement after permission granted
}
}
public boolean isStoragePermissionGranted() {
String TAG = "logcheck";
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED ) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
boolean flag;
flag = true;
if(requestCode == 1)
{
for (int i:grantResults)
{
if( i == PackageManager.PERMISSION_DENIED)
flag = false;
}
if (flag)
{
Intent intent = new Intent(this,MainActivity.class);
finish();
startActivity(intent);
}
}
}
}
Diego Cortés
Updated on June 30, 2022Comments
-
Diego Cortés almost 2 years
Hi everyone I have a problem with load activity elements after checking runtime permission I made a app for Lollipop but now I need update to Marshmallow so I have this problem
I have a MainActivity
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if(checkAndRequestPermissions(this)) { //Var created Internetstatus = (TextView) findViewById(R.id.statusInternet); if (!verificaConexion(this)) { Internetstatus.setText("NOT CONNECTED"); } else { Internetstatus.setText("CONNECTED"); } } } public static boolean verificaConexion(Context ctx) { boolean bConectado = false; ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { bConectado = true; } return bConectado; } private boolean checkAndRequestPermissions(Context ctx) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Toast.makeText(this, "Checking permission…", Toast.LENGTH_SHORT).show (); //List of permissions int permissionInternet = ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET); int permissionAccessNetwork = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE); int permissionReadExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE); int permissionWriteExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); List<String> listPermissionsNeeded = new ArrayList<>(); //Verify status of permissions if (permissionInternet != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.INTERNET); } if (permissionAccessNetwork != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE); } if (permissionReadExternal != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE); } if (permissionWriteExternal != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS); return false; } return true; } return true; } }
Right, I have more elements in the activity but with the only single text is fine for the example :), the checking permission is fine but when I press allow the permissions the activity text status is the default text xD! "Small Text", so the setText not work, but if I close the app and open again all work perfectly because I have allowed the permission yet. Hey is my first time that I make app for marshmallow, so maybe the problem is very stupid hahahha.
Well after that dont work I thought that maybe if I create a new activity LoadActivity I can check the permissions there (move function check and all about check permission from MainActivity to LoadActivity) and if the conditional is fine I initialize the MainActivity, this fine start new activity (LoadActivity), I check permissions but start the MainActivity dont work after I allow permissions
The new LoadActivity is
public class LoadActivity extends AppCompatActivity { public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_load); if(checkAndRequestPermissions(this)) { Intent intent = new Intent(this, MainActivity.class); startActivityForResult(intent, 0); } } private boolean checkAndRequestPermissions(Context ctx) { if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Toast.makeText(this, "Checking permission…", Toast.LENGTH_SHORT).show (); //List of permissions int permissionInternet = ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET); int permissionAccessNetwork = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE); int permissionReadExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE); int permissionWriteExternal = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); List<String> listPermissionsNeeded = new ArrayList<>(); //Verify status of permissions if (permissionInternet != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.INTERNET); } if (permissionAccessNetwork != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE); } if (permissionReadExternal != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.READ_EXTERNAL_STORAGE); } if (permissionWriteExternal != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS); return false; } return true; } return true; } }
I hope someone can help me :D Regards