Write to external storage on Android 7 - java

I want to write to the external storage in my Android app, but I don't seem to get the permissions right. The App runs on Android 7, so I request the permissions on runtime like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
int ACCESS_EXTERNAL_STORAGE_STATE = 1;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
ACCESS_EXTERNAL_STORAGE_STATE);
}
permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
int ACCESS_EXTERNAL_STORAGE_STATE = 1;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
ACCESS_EXTERNAL_STORAGE_STATE);
}
...
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case 1: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
//reload my activity with permission granted or use the features what required the permission
} else
{
Toast.makeText(this, "The app was not allowed to write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
One observation I made is that onRequestPermissionsResult seems to return that the permission was not granted, but I was also never prompted when starting the app to permit writing to external storage.
I set these permissions in the Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application>
The code to write to the storage is here:
public static void appendByteBuffer(byte[] data)
{
String filename = Environment.getExternalStorageDirectory().getAbsolutePath()+"/test.raw";
//filename value is "/storage/emulated/0/test.raw"
File rawAudioFile = new File(filename);
if (!rawAudioFile.exists())
{
try
{
rawAudioFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try (FileOutputStream output = new FileOutputStream(filename, true)) {
output.write(data);
} catch (IOException e) {}
}
03-16 14:50:49.988 19145-19306/? W/System.err: java.io.IOException:
Permission denied 03-16 14:50:49.988 19145-19306/? W/System.err:
at java.io.UnixFileSystem.createFileExclusively0(Native Method) 03-16
14:50:49.988 19145-19306/? W/System.err: at
java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:280)
03-16 14:50:49.989 19145-19306/? W/System.err: at
java.io.File.createNewFile(File.java:948) 03-16 14:50:49.989
19145-19306/? W/System.err: at
com.meeter.study.AppUtils.appendByteBuffer(AppUtils.java:76) 03-16
14:50:49.989 19145-19306/? W/System.err: at

Use ContextCompat instead of ActivityCompat for checkSelfPermission:
Replace:
permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
With:
permission = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
permission = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
Then, Add onRequestPermissionsResult method to handle ALLOW, DENY selection. Hope this helps.
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case ACCESS_EXTERNAL_STORAGE_STATE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Write to the storage (ex: call appendByteBuffer(byte[] data) here)
} else {
Toast.makeText(getApplicationContext(), "Please grant permission.", Toast.LENGTH_LONG).show();
}
break;
}
}

Related

Android 13 (Tiramisu) Emulator Debug App Notification can't be turn on

Any idea how to enable the permission on the app? the permission was disabled by default on Android 13 Emulator. It was working on other emulator, just not Android 13 Emulator. By default, adding Firebase Messaging will add the Manifest.permission.POST_NOTIFICATIONS into the Manifest.
requestPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS);
auto return isGranted = false
in Manifest:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
This is how to request and check results for runtime for api13
private void request_notification_api13_permission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (this.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.POST_NOTIFICATIONS}, 22);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 22) {
if (grantResults.length > 0)
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted, perform required code
} else {
// not granted
}
}
}
calling function will be like this:
request_notification_api13_permission();

Android TelephonyManager Permissions

I am trying to code a quick application which gives me the needed 3G values, when I click a button.
But first I need to check if I am connected to 3G network.
However I am having some issues with my Permissions.
I am having the following code:
public void calculate(View view) {
TextView rscp = (TextView) findViewById(R.id.RSCP);
TextView rssi = (TextView) findViewById(R.id.RSSI);
TextView ecno = (TextView) findViewById(R.id.EcNo);
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (Arrays.stream(values_3G).anyMatch(n -> n == tm.getDataNetworkType())) {
for (CellInfo cellInfo : tm.getAllCellInfo()) {
if (cellInfo instanceof CellInfoWcdma) {
CellSignalStrengthWcdma cellSignalStrength = ((CellInfoWcdma) cellInfo).getCellSignalStrength();
rscp.setText(cellSignalStrength.getDbm());
ecno.setText(cellSignalStrength.getEcNo());
int rssiValue = -113 + 2 * cellSignalStrength.getAsuLevel();
rssi.setText(rssiValue);
}
}
} else {
rscp.setText(0);
rssi.setText(0);
ecno.setText(0);
Log.i(TAG, "No 3G Mobile connection detected!");
Toast.makeText(getApplicationContext(), "Connect to 3G", Toast.LENGTH_SHORT).show();
}
}
tm.getDataNetworkType() is giving me the following issue with READ_PHONE_STATE:
Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException
If I follow the instructions to check permission in Android Studio I get the following:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
What do I need to fill in between the brackets?
Create a global final int of the permission request code
final int PHONE_REQUEST_CODE = 101;
And request the permission if not granted
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
PHONE_REQUEST_CODE); // triggers onRequestPermissionsResult()
} else {
// calculate(myView); // Do whatever you want as the permission is already granted
}
And override onRequestPermissionsResult() in activity
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length == 0)
return;
if (requestCode == PHONE_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// calculate(myView); // Do whatever you want after the permission is granted
}
And add the permission in manifest.xml as well.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

external storage not available

I want create new file and write/read app settings. isExternalStorageAvailable() return false and should true. Android emulator external memory = 200mb.
boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
Added permissions to manifest file:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
System.out.println("Available: "+isExternalStorageAvailable()+", ReadOnly: "+isExternalStorageReadOnly());
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
}
To get all external storage paths this can be used:
File[] extSDCardPaths = null;
try {
extSDCardPaths = ContextCompat.getExternalFilesDirs(ctx, null);
} catch (Exception e) {
// handle
}
for (File f : extSDCardPaths) {
if (Environment.isExternalStorageRemovable(f)) {
// check if anything found
}
}
If extSDCardPaths returns something then ext storage is available.
The above works for > 4.4(KitKat) only
The below hack can be used as fallback for lower OS versions:
String[] fallback = {"/storage/sdcard1/", "/mnt/ext_card/", "/mnt/extSdCard/", "/storage/extsdcard/",
"/mnt/extsdcard/", "/storage/extSdCard/", "/mnt/external_sd", "/storage/MicroSD/",
"/storage/external_SD/", "/storage/ext_sd/", "/storage/removable/sdcard1/", "/mnt/sdcard/external_sd/",
"/storage/ext_sd/", "/mnt/emmc/", "/data/sdext/", "/sdcard/sd/"};
for (String path : fallback) {
if (new File(path).exists()) {
// found an ext. dir
break;
}
}
If your application is targeting and running on marshmallow or above, you must gain permission to read/write to external storage, you must request permission from user explicitly after declaring permission in manifest.
Make sure you have this in your manifest: <uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Check for permission explicitly. If not provided, request it:
public void checkPermissionReadStorage(Activity activity){
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_STORAGE);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
Receive permission response:
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PermissionManager.MY_PERMISSIONS_REQUEST_READ_STORAGE:
//premission to read storage
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted. Call your storage related code here
} else {
// permission denied.
// Handle permission failed here.
}
return;
// other 'case' lines to check for other
// permissions this app might request
}
}
Code was taken from here

Android contacts permission granted without asking at runtime

I'm trying to request the ability to read contacts in an app, and have followed several tutorials. All of these use nearly the same code for this process. Below is the code in my MainActivity.java file, that should request permission.
private void checkContactPermissions()
{
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Contacts permission NOT granted");
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
else
{
Log.i(TAG, "Contacts permission granted");
readContacts();
}
}
My manifest.xml also includes the line:
<uses-permission android:name="android.permission.READ_CONTACTS" />
When the app is run, either on emulator or physical debugging device, it does not ask for permission, however the log states that the permission was granted. I have confirmed the permission is off by going to the settings and checking it was turned off. What else would be causing the app to perform as if permissions were granted.
Try this,
private Context mContext=YourActivity.this;
private static final int REQUEST = 112;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.READ_CONTACTS};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST );
} else {
readContacts();
}
} else {
readContacts();
}
get Permissions Result
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readContacts();
} else {
Toast.makeText(mContext, "The app was not allowed to read your contact", Toast.LENGTH_LONG).show();
}
}
}
}
check permissions for marshmallow
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
Manifest
<uses-permission android:name="android.permission.READ_CONTACTS" />
I use RxPermission for permissions to make my code ultimately short.
First add these permissions (or one you need) in your manifest.xml.
<uses-permission android:name="android.permission.READ_CONTACTS" />
Then ask run time permission from user in your activity.
RxPermissions rxPermissions = new RxPermissions(this);
rxPermissions
.request(Manifest.permission.READ_CONTACTS) // ask single or multiple permission once
.subscribe(granted -> {
if (granted) {
// All requested permissions are granted
} else {
// At least one permission is denied
}
});
add this library in your build.gradle
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.tbruyelle:rxpermissions:0.10.1'
implementation 'com.jakewharton.rxbinding2:rxbinding:2.1.1'
}
Isn't this easy?
As Divyesh Patel pointed out, I had the boolean statemetns mixed up, it should be
ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)
Rather than
ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)
Important thing for you to note here that these permissions are asked only for devices with version>23 and if you have lower version of android then for only some models like redmi you have to invoke the permissions manually .
Otherwise version<23 generally do not ask for permissions.
If you put in manifest. It will automatically take it, specially when you are installing app over usb.
If any device has OS version below <23 or In app manifist file maxtarget version is below <23 then it will not ask permission in runtime because while the app installing on these devices you actually giving permission to all you mentioned.
So the runtime permissions are possible only in the case of device has OS version above 22(Lolipop).
Hope this helpful..
#Rajesh

How to ask permission to make phone call from Android from Android version Marshmallow onwards?

I am trying to make a phone call from Android, and I've set run time permissions as well. And it asks whether to allow making phone calls. But when I press allow, the app crashes:
This is how I implemented it:
private static final int REQUEST_PHONE_CALL = 1;
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "+918511812660"));
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE},REQUEST_PHONE_CALL);
}
else
{
startActivity(intent);
}
}
else
{
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_PHONE_CALL: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startActivity(intent);
}
else
{
}
return;
}
}
}
This is what I obtain in logcat:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=#android:requestPermissions:,
request=1, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }}
to activity {com.devpost.airway/com.devpost.airway.activities.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.content.Intent.toString()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3733)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String android.content.Intent.toString()' on a null object reference
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
at android.app.Activity.startActivityForResult(Activity.java:3930)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
at android.app.Activity.startActivityForResult(Activity.java:3890)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:856)
at android.app.Activity.startActivity(Activity.java:4213)
at android.app.Activity.startActivity(Activity.java:4181)
at com.devpost.airway.activities.MainActivity.onRequestPermissionsResult(MainActivity.java:140)
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:6582)
at android.app.Activity.dispatchActivityResult(Activity.java:6460)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3729)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3776)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1412)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
What is possibly causing this?
I would better suggest to use ACTION_DIAL rather than ACTION_CALL while constructing Intent to call a particular number . Using ACTION_DIAL , you will need no call permissions in your app, as ACTION_DIAL opens the dialer with the number already entered, and further allows the user to decide whether to actually make the call or modify the phone number before calling or not call at all.
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "Your Phone_number"));// Initiates the Intent
startActivity(intent);
The stack trace seems to indicate that your permissions flow is working ok, but the call to startActivity from onRequestPermissionsResult() is crashing. Is the Intent you're passing to startActivity set correctly? I can't see it being set in that part of the code.
Note also that ContextCompat.checkSelfPermission handles the SDK version checking on your behalf, so you should be able to use
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CALL_PHONE},REQUEST_PHONE_CALL);
}
else
{
startActivity(intent);
}
by itself, without the wrapping SDK version check code.
You need to create your Intent in onRequestPermissionsResult
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_PHONE_CALL: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "+918511812660"));
startActivity(intent);
}
else
{
}
return;
}
}
}
add new method
public static boolean hasPermissions(Context context, String... permissions) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
add this in Global
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {Manifest.permission.READ_CONTACTS, Manifest.permission.CALL_PHONE};
and write below code in onCreate
if(!hasPermissions(this, PERMISSIONS)){
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
It is better to not use phone_call permission for that action. Google Play console will alert you that you should avoid asking for unnecessary permission from the user. This is a better approach:
/**
* Make a phone call. Send to the phone app
*
* #param phoneNumber the phone number to call
*/
private fun performPhoneCall(phoneNumber: String) {
val intent = Intent(Intent.ACTION_DIAL)
intent.data = Uri.parse("tel:$phoneNumber")
try {
context.startActivity(intent)
} catch (ex: Exception) {
displayErrorMessage()
}
}
Change your onRequestPermissionsResult to below, you basically need to create the intent first and then call it on permission granted. That's where you are doing it wrong.
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_PHONE_CALL : {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "+918511812660"));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
startActivity(intent);
}
}
}
}
}
private void makePhoneCall() {
String number = items;
if (number.trim().length() > 0) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CALL);
} else {
String dial = "tel:" + number;
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(dial)));
}
} else {
Toast.makeText(MainActivity.this, "Enter Phone Number", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == REQUEST_CALL) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
makePhoneCall();
} else {
Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
}
}
}

Categories