i can't read the user storage, - java

I' am trying to list all the folders and files from user storage, I've declared the READ_EXTERNAL_STORAGE permission in android.manifest file but I don't what's wrong, I can't read the user storage
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(this);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[] {
Manifest.permission.READ_EXTERNAL_STORAGE
}, 123);
} else {
Log.d(TAG, "onCreate: Permission Granted");
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case 123:
if (grantResults != null && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission Denied",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
String path = "/";
File dir = new File(path);
if (dir.isDirectory()) {
Log.d(TAG, "dir: Yes, I am!");
}
if (dir.canRead()) {
Log.d(TAG, "dir: Read me!");
} else {
Log.d(TAG, "dir: you can't read me!");
}
if (dir.canWrite()) {
Log.d(TAG, "dir: use me!");
} else {
Log.d(TAG, "dir: You Can't write me");
}
}
}
}
log cat: D/MainActivity: onCreate: Permission Granted 2020-05-04
07:21:09.680 27634-27634/co.ak.externalstorage D/MainActivity: dir:
Yes, I am! 2020-05-04 07:21:09.680 27634-27634/co.ak.externalstorage
D/MainActivity: dir: you can't read me! 2020-05-04 07:21:09.680
27634-27634/co.ak.externalstorage D/MainActivity: dir: You Can't write
me

The "/" root directory is not readable since Android 7.
Why are you calling that user storage?

Related

Can't request bluetooth premission on android

Hello I've been struggling with requesting the following bluetooth permissions on Android Studio: BLUETOOTH_CONNECT, BLUETOOTH_SCAN, BLUETOOTH_ADVERTISE but none of them wants to be requested: I'm using the following code to request BLUETOOTH_SCAN permission:
public class MainActivity extends AppCompatActivity {
private final int BLUETOOTH_PERMISSION_CODE = 4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonRequest = findViewById(R.id.button);
buttonRequest.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.S)
#Override
public void onClick(View v) {
if (
ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED
) {
Toast.makeText(MainActivity.this, "You have already granted this permission!",
Toast.LENGTH_SHORT).show();
} else {
requestStoragePermission();
}
}
});
}
#RequiresApi(api = Build.VERSION_CODES.S)
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.BLUETOOTH_SCAN)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This permission is needed because of this and that")
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.BLUETOOTH_SCAN}, BLUETOOTH_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.BLUETOOTH_SCAN}, BLUETOOTH_PERMISSION_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == BLUETOOTH_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission GRANTED", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}
}
And there is also a manifest file which contains the following content:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-feature android:name="android.hardware.bluetooth"/>
unfortunately this code doesn't work. It always shows permission denied. It doesn't even display dialog But if I want to request for example READ_EXTERNAL_STORAGE premision it works without any problems could you tell me guys why is this happening? Can't bluetooth permissions be requested by the way from above? Best wishes and waiting for help!

How to make a class from that code? In order to not mess the Activity with a ton of code

I want create a class called Permissions from below code and then call that in a click of a button. Because there is an #Override method in this activity and I don't know how to override methods inside a class. If I make a class for it the code would be much cleaner and easier to understand.
public class MainActivity extends AppCompatActivity {
TextView textView;
Button button;
final int REQUEST_CODE_FINE_LOCATION = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
button = findViewById(R.id.button);
// we are going to test weather the Location Permission is granted or not
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
textView.setText("Permission Granted...");
} else {
textView.setText("Permission is NOT granted");
}
}
public void requestPermission(View view) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Permission is NOT granted
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(MainActivity.this)
.setMessage("We need permission for fine location")
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_FINE_LOCATION);
}
})
.show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_FINE_LOCATION);
}
} else {
// Permission is Granted
textView.setText("Permission Granted");
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_FINE_LOCATION) {
if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permission Granted
textView.setText("Permission is Granted");
} else {
//Permission NOT granted
if (!ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
//This block here means PERMANENTLY DENIED PERMISSION
new AlertDialog.Builder(MainActivity.this)
.setMessage("You have permanently denied this permission, go to settings to enable this permission")
.setPositiveButton("Go to settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
gotoApplicationSettings();
}
})
.setNegativeButton("Cancel", null)
.setCancelable(false)
.show();
} else {
//
textView.setText("Permission NOt granted");
}
}
}
}
private void gotoApplicationSettings() {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", this.getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}
Source: https://github.com/trulymittal/RuntimePermission
Use TedPermission Library which is very easy to use and easy to handle .
Make a Function in separate class and use it anywhere you want
implementation 'gun0912.ted:tedpermission:2.2.3'
public void checkPermissions(Context context) {
PermissionListener permissionlistener = new PermissionListener() {
#Override
public void onPermissionGranted() {
Toast.makeText(context, "Permission Granted", Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionDenied(List<String> deniedPermissions) {
Toast.makeText(context, "Permission Denied\n" + deniedPermissions.toString(), Toast.LENGTH_SHORT).show();
}
};
TedPermission.with(context)
.setPermissionListener(permissionlistener)
.setDeniedMessage("If you reject permission,you can not use this service\n\nPlease turn on permissions at [Setting] > [Permission]")
.setPermissions(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
.check();
}
https://github.com/ParkSangGwon/TedPermission
You can make interface hold all the methods and create abstract class implement the interface then make any classes that inherit from the abstract class read about liskov and segregation principles

How to show AlertDialog as permission rationale

I have two activities: a Main, as well a RuntimePermissionManager, which is started first whenever my app is opened.
The app works as expected when the user allows the runtime permission, but when they deny it, instead of the AlertDialog showing up with the permission rationale, the permission dialog is closed completely, and I just get an infinite splash screen (since I have set it to always be on screen during the lifetime of its parent activity).
I have copied the permission logic straight from the RuntimePermissionsBasic example bundled with Android Studio, and just replaced the Snackbar with an AlertDialog, so I don’t see why my app isn’t working.
Here’s the complete RuntimePermissionManager activity for reference.
Thanks.
public class RuntimePermissionManager extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final String TAG = "RuntimePermissionManager";
private static final String PERMISSION = Manifest.permission.WRITE_EXTERNAL_STORAGE;
private static final int PERMISSION_ID = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
final SplashScreen splashScreen = SplashScreen.installSplashScreen(this);
super.onCreate(savedInstanceState);
// This ensures no hiccups while the splash screen is active.
splashScreen.setKeepOnScreenCondition(() -> true);
checkRuntimePermissionStatus();
ThreadManager.unpackCriticalAssets(getApplicationContext());
}
#Override
public void onRequestPermissionsResult(final int requestCode, #NonNull final String[] permissions, #NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PERMISSION_ID) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Runtime permission has been granted.");
startMainActivity();
} else {
Log.e(TAG, "Runtime permission has been denied.");
}
}
}
private void checkRuntimePermissionStatus() {
if (ActivityCompat.checkSelfPermission(this, PERMISSION) == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Runtime permission has been granted.");
startMainActivity();
} else {
requestRuntimePermission();
}
}
private void requestRuntimePermission() {
System.out.println(ActivityCompat.shouldShowRequestPermissionRationale(this, PERMISSION));
if (ActivityCompat.shouldShowRequestPermissionRationale(this, PERMISSION)) {
System.out.println("HERE1");
showPermissionRationaleDialog(R.string.permission_rationale_title, R.string.permission_rationale_message);
} else {
Log.e(TAG, "Runtime permission has been denied.");
ActivityCompat.requestPermissions(this, new String[]{PERMISSION}, PERMISSION_ID);
}
}
private void showPermissionRationaleDialog(final int title, final int message) {
System.out.println("HERE2");
AlertDialog.Builder builder = new AlertDialog.Builder(RuntimePermissionManager.this);
builder.setTitle(title).setMessage(message).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(RuntimePermissionManager.this, new String[]{PERMISSION}, PERMISSION_ID);
}
});
builder.create().show();
}
private void startMainActivity() {
Intent intent = new Intent(this, Main.class);
startActivity(intent);
}
}

onRequestPermissionResult not being called in AppCompatActivity

I am trying to request some permission for my app inside the launcher activity. This activity only checks for permissions and prompts the user asking for missing permission. What I want to do is after 1.5 seconds, if the user was prompted and accepted/denied the permissions required, the main activity is started, displaying the dashboard of the application. Now, the problem is that onRequestPermissionResult is not called no matter what I do and I don't understand where the problem comes from. I mention that the permissions are requested successfully, the user being prompted and being able to accept them or deny them, but the callback is not triggered somehow.
Here is my activity code:
public class LauncherActivity extends AppCompatActivity {
public static final String TAG = LauncherActivity.class.getSimpleName();
private boolean permissionsGiven;
private static final String[] REQUIRED_PERMISSIONS =
new String[] {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
};
private static final int REQUEST_CODE_REQUIRED_PERMISSIONS = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
if (!hasPermissions(this, REQUIRED_PERMISSIONS)) {
permissionsGiven = false;
Log.d(TAG, "onCreate: app does not have all the required permissions. Requesting permissions...");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(
this,
REQUIRED_PERMISSIONS,
REQUEST_CODE_REQUIRED_PERMISSIONS
);
}
} else {
permissionsGiven = true;
}
Runnable enterApplication = new Runnable() {
#Override
public void run() {
while (!permissionsGiven);
SharedPreferences loginPreferences = getApplicationContext().getSharedPreferences("LOGIN_DETAILS", MODE_PRIVATE);
boolean signedIn = loginPreferences.getBoolean("signedIn", false);
if (!signedIn) {
Log.d(TAG, "onCreate: user is not signed in. Sending him to login activity...");
sendUserToLoginActivity();
} else {
sendUserToMainActivity();
}
}
};
Handler launcherHandler = new Handler();
launcherHandler.postDelayed(enterApplication, 1500);
}
private static boolean hasPermissions(Context context, String... permissions) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
#CallSuper
#Override
public void onRequestPermissionsResult(
int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode != REQUEST_CODE_REQUIRED_PERMISSIONS) {
return;
}
permissionsGiven = true;
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Missing permissions", Toast.LENGTH_LONG).show();
finish();
return;
}
}
recreate();
}
private void sendUserToLoginActivity() {
Log.d(TAG, "sendUserToLoginActivity: starting login activity...");
Intent loginIntent = new Intent(LauncherActivity.this, SignInActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(loginIntent);
finish();
}
private void sendUserToMainActivity() {
Log.d(TAG, "sendUserToMainActivity: starting main activity...");
Intent mainIntent = new Intent(LauncherActivity.this, MainActivity.class);
mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainIntent);
finish();
}
}
Can anyone help me understand what am I doing wrong and how can I trigger onRequestPermissionsResult so I can start the next activity inside the app?
recreate();
I never saw that method.
Dont call it for a test and place a Toast instead.
I wonder how you know that it is not triggered.
Further i would not use a thread that is waiting for a variable to change its value.
Further you dont need threads at all. Just call the code in onCreate or onRequestPermissionsResult. You can place all that code in a function.

ActivityCompat can't find .checkSelfPermission in eclipse

I have create program which can send message. when I use Activity.checkSelfPermission, it show the error like "The method checkSelfPermission(MainActivity, String) is undefined for the type ActivityCompat". I have import android.support.v4.app.ActivityCompat already. My target API 23 and compile with API 23 also. How to solve it?
Below is the real code
public class MainActivity extends Activity {
public static final int MY_PERMISSION_SEND_SMS = 10;
public EditText edSMS, edPhone;
public Button btnSent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edSMS = (EditText)findViewById(R.id.editText1);
edPhone = (EditText)findViewById(R.id.editText2);
btnSent = (Button)findViewById(R.id.button1);
onCheckPermission();
}
private void onCheckPermission() {
if(ActivityCompat.checkSelfPermission(this,Manifest.permission.SEND_SMS)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermission(this, new String[]{Manifest.permission.SEND_SMS}, MY_PERMISSION_SEND_SMS);
}
else {
sentMessage();
}
}
private void sentMessage() {
btnSent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String phoneNumber = edPhone.getText().toString();
String SMS = edSMS.getText().toString();
if(((phoneNumber.length() == 10) || (phoneNumber.length()==9)) && phoneNumber.length()>0){
SmsManager smsText = SmsManager.getDefault();
smsText.sendTextMessage(phoneNumber, null, SMS, null, null);
Toast.makeText(MainActivity.this, "SMS was sent successful", Toast.LENGTH_LONG).show();
edPhone.setText("");
edSMS.setText("");
} else {
Toast.makeText(MainActivity.this, "Please check your " + "phone number again",Toast.LENGTH_LONG).show();
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
switch (requestCode){
case MY_PERMISSION_SEND_SMS:
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Read Contacts permission granted", Toast.LENGTH_SHORT).show();
sentMessage();
}else{
Toast.makeText(this, "Read Contacts permission denied", Toast.LENGTH_SHORT).show();
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS)){
new AlertDialog.Builder(this).
setTitle("Request Permission SMS").
setMessage(" You must set permission to access this application").show();
}
}
break;
}
}
To solve the method ActivityCompat.checkSelfPermission() not found in Eclipse you can simply add android-support-compat.jar as taken from https://github.com/dandar3/android-support-compat/tree/28.0.0 to the libs folder of your Eclipse project and compile again.
just use support.v7 (import android.support.v7.app.AppCompatActivity;),this is well be rolved
by the way?why do you still use eclipse now?just use Android studio,it's better so much.

Categories