This question already has answers here:
How to make a phone call using intent in Android?
(21 answers)
How to make a phone call programmatically?
(10 answers)
How to make a phone call button in Android for Marshmallow
(3 answers)
How to ask permission to make phone call from Android from Android version Marshmallow onwards?
(7 answers)
Closed 4 years ago.
I used following code for phone call.But the call is not working .can anyone help me? I also given manifest Call Phone permission.
call = (TextView) findViewById(R.id.GuestPhoneNo1);
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String no = call.getText().toString();
// Toast.makeText(Accepted_Details.this, no, Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + no));
/*if (ActivityCompat.checkSelfPermission(Accepted_Details.this, Manifest.permission.CALL_PHONE) != 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;
}*/
startActivity(callIntent);
}
You can use the following code,
I also add the permission popup for above marshmallow.
Uri call = Uri.parse("tel:" + mobile_number);
Intent surf = new Intent(Intent.ACTION_CALL, call);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(TrackActivity.this, Manifest.permission.CALL_PHONE)) {
ActivityCompat.requestPermissions(TrackActivity.this, new String[]{Manifest.permission.CALL_PHONE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
} else if (permissionStatus.getBoolean(Manifest.permission.CALL_PHONE, false)) {
AlertDialog.Builder builder = new AlertDialog.Builder(TrackActivity.this);
builder.setTitle("Need call Permission");
builder.setMessage("This app needs call permission.");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
Toast.makeText(getBaseContext(), "Go to Permissions to Grant call", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else {
ActivityCompat.requestPermissions(TrackActivity.this, new String[]{Manifest.permission.CALL_PHONE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
}
SharedPreferences.Editor editor = permissionStatus.edit();
editor.putBoolean(Manifest.permission.CALL_PHONE, true);
editor.apply();
} else {
startActivity(surf);
}
Even with having added the permissions in the manifest file you need to request for the permission before you run the code that makes the call
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, MAKE_CALL_PERMISSION_REQUEST_CODE);
the whole thing could look like this
public class MainActivity extends AppCompatActivity {
private static final int MAKE_CALL_PERMISSION_REQUEST_CODE = 1;
private Button dial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dial = (Button) findViewById(R.id.dial);
final EditText numberToDial = (EditText) findViewById(R.id.number);
dial.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String phoneNumber = numberToDial.getText().toString();
if (!TextUtils.isEmpty(phoneNumber)) {
if (checkPermission(Manifest.permission.CALL_PHONE)) {
String dial = "tel:" + phoneNumber;
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse(dial)));
} else {
Toast.makeText(MainActivity.this, "Permission Call Phone denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a phone number", Toast.LENGTH_SHORT).show();
}
}
});
if (checkPermission(Manifest.permission.CALL_PHONE)) {
dial.setEnabled(true);
} else {
dial.setEnabled(false);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, MAKE_CALL_PERMISSION_REQUEST_CODE);
}
}
private boolean checkPermission(String permission) {
return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch(requestCode) {
case MAKE_CALL_PERMISSION_REQUEST_CODE :
if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
dial.setEnabled(true);
Toast.makeText(this, "You can call the number by clicking on the button", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
Related
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
I am making an application that is supposed to dial a number after a button has been clicked on. All I want is to do is for the action to be performed immediately after the first permission request.
//everything here is in an onClickListener
//number is already specified
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse(String.format("tel:%s", Uri.encode(number))));
if(ActivityCompat.checkSelfPermission(activity,
Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED){
activity.startActivity(callIntent);
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//if Api >= 23
if(activity.shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE)){
//WHY THIS PERMISSION IS NEEDED
final String why_the_permission_is_needed = "why it is needed";
new AlertDialog.Builder(activity)
.setTitle("WHY THIS PERMISSION IS NEEDED")
.setMessage(why_the_permission_is_needed)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.create().show();
}
}
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CALL_PHONE}, DIAL_PERMISSION_REQUEST_CODE);
if(ActivityCompat.checkSelfPermission(activity,
Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED){
activity.startActivity(callIntent);
}
}
What happens is that before
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CALL_PHONE}, DIAL_PERMISSION_REQUEST_CODE);
is done the remaining code
if(ActivityCompat.checkSelfPermission(activity,
Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED){
activity.startActivity(callIntent);
}
would have been executed. Meaning the user will have to click on the button once to get the permission and again to actually perform the intent, which is what I do not want.
Also
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CALL_PHONE}, DIAL_PERMISSION_REQUEST_CODE);
returns void.
You should override onRequestPermissionsResult on your activity and handle the requested permission result. To be able to reinvoke your process, declare your click listener algorithm in a function and recall it when the result was ready:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performCall();
}
})
And then process the result:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull #NotNull String[] permissions, #NonNull #NotNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0) {
if (requestCode == DIAL_PERMISSION_REQUEST_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
performCall();
}
}
}
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.
My Android application crashes the first time launching and it asks me about the user call permission. When I launch my app again then it works normally. I have tried the following code.
public void loadContactList() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
} else {.....}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
loadContactList();
} else {
Toast.makeText(this, "Until you grant the permission, we canot display the list", Toast.LENGTH_SHORT).show();
}
}
}
Your code is right but you set the codes on wrong places lets try this it will definitely help you....
In Your Main Activity...
private int STORAGE_PERMISSION_CODE = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
PackageManager.PERMISSION_GRANTED) {
filter();
Toast.makeText(this, ""+arrayList, Toast.LENGTH_SHORT).show();
} else {
Permission.requestStoragePermission(MainActivity.this,
STORAGE_PERMISSION_CODE);
}
}//on create closed
Permission method.....
//---------------------------------RuntimePermission-----------------------------//
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] grantResults) {
if (requestCode == STORAGE_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
filter();
} else {
Toast.makeText(this, "Permission DENIED", Toast.LENGTH_SHORT).show();
Permission.requestStoragePermission(MainActivity.this,STORAGE_PERMISSION_CODE);
}
}
}
after that make java class for getting permission....
public class Permission {
public static void requestStoragePermission(final Activity activity, final int
STORAGE_PERMISSION_CODE) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(activity)
.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(activity,
new String[]
{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
STORAGE_PERMISSION_CODE);
}
}
}
The main thing you have to remember is to put your working method at the right place like my is filter();
It will work for you because it work for me when i stuck in the same situation
Add the following code
String[] appPermissions =
{Manifest.permission.READ_CONTACTS,
Manifest.permission.WRITE_CONTACTS};
int PERMISSIONS_REQUEST_CODE = 234;
Call this Method from your on create
checkAndRequestPermissions();
Add the following method to your Main Activity
public boolean checkAndRequestPermissions() {
List<String> listPermissionsNeeded = new ArrayList<>();
for (String perm : appPermissions) {
if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(perm);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), PERMISSIONS_REQUEST_CODE);
return false;
}
return true;
}
I just solved an exception. I did two things. Firstly, I removed the initialization of Contacts by
Contacts = new ArrayList<ContactModel> from the loadContactList() and added it into the onCreate() and Secondly I just changed the return datatype of loadContactList() from void to list. Then I returned the contacts in loadContacts() so that loadListView() can fetch this list and display it into the list view.
i have method for get runtime permission i searched for that long but still have no answer can anyone help me to modify my code ? cause its never show request dialog for get user permission after user accept permission move to next activity
here my code that i made but some how its never made a request
public class perm extends AppCompatActivity {
private static final int REQUEST_PERMISSION_SETTING = 200;
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dash);
isPermissionGranted();
}
public boolean isPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.CALL_PHONE)
== 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.CALL_PHONE}, REQUEST_PERMISSION_SETTING);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG","Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(permissions.length == 0){
return;
}
boolean allPermissionsGranted = true;
if(grantResults.length>0){
for(int grantResult: grantResults){
if(grantResult != PackageManager.PERMISSION_GRANTED){
allPermissionsGranted = false;
break;
}
}
}
if(!allPermissionsGranted){
boolean somePermissionsForeverDenied = false;
for(String permission: permissions){
if(ActivityCompat.shouldShowRequestPermissionRationale(this, permission)){
//denied
Log.e("denied", permission);
}else{
if(ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED){
//allowed
Log.e("allowed", permission);
} else{
//set to never ask again
Log.e("set to never ask again", permission);
somePermissionsForeverDenied = true;
}
}
}
if(somePermissionsForeverDenied){
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Permissions Required")
.setMessage("You have forcefully denied some of the required permissions " +
"for this action. Please open settings, go to permissions and allow them.")
.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setCancelable(false)
.create()
.show();
}
} else {
switch (requestCode) {
//act according to the request code used while requesting the permission(s).
}
}
}
}