call by phone number on button click (java) - java

I have a call method on button click
button_call=(Button) findViewById(R.id.button_call);
button_call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+79142214017"));
startActivity(intent);
}
});
And the data transfer method in Firebase
private void validateClientInfo() {
if (TextUtils.isEmpty(client_edit.getText().toString())) {
Toast.makeText(this, "Введите имя", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(client_number.getText().toString())){
Toast.makeText(this, "Введите номер", Toast.LENGTH_SHORT).show();
}
else {
HashMap<String, Object> userMap = new HashMap<>();
userMap.put("uid", mAuth.getCurrentUser().getUid());
userMap.put("numberphone_client",client_number.getText().toString());
clientRef.child(mAuth.getCurrentUser().getUid()).updateChildren(userMap);
startActivity(new Intent(ClientName.this,HomeActivity.class));
}
}
transcripts
client_number=(EditText) findViewById(R.id.client_number);
mAuth=FirebaseAuth.getInstance();
how to make it so that when the call button is pressed, the number is received and called?
I want that when the button _call button is pressed, the data transmitted by the transfer method is received and a call is made on them.

Request permission android.permission.CALL_PHONE before calling.
Add into AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
Request permission before calling:
boolean isPermissionGranted = (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED);
if (isPermissionGranted) {
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + mNumber));
startActivity(intent);
} else {
Toast.makeText(this, "Отсутствует разрешение на звонок с устройства", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.CALL_PHONE }, 0);
}
Add request result:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull #NotNull String[] permissions, #NonNull #NotNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 0) {
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
//RETURN, PERMISSION NOT GRANTED
Toast.makeText(this, "Вы не выдали разрешение, приложение может работать неккоректно!", Toast.LENGTH_SHORT).show();
return;
}
}
//PERMISSIONS GRANTED
Toast.makeText(this, "Спасибо за выданное разрешение!", Toast.LENGTH_SHORT).show();
}
}

If your are looking to call the selected number then just use the following code.
Intent intentCallForward = new Intent(Intent.ACTION_DIAL); // ACTION_CALL
Uri uri2 = Uri.fromParts("tel", "79142214017, "#");
intentCallForward.setData(uri2);
startActivityForResult(intentCallForward, 101);

Related

My app keep showing "permission denied can't use the app"

My app is an sos app that can send an sms with location by shaking the phone to a saved contact.
But when i want to try my app it keep show me "permission denied can't use the app" although i added the permission (contact and location and sms)
Can you please help me to solve this problem
This is my code :
Button button1;
ListView listView;
databaseOpenHelper db;
List<ContactModel> list;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone);
// check for runtime permissions
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.SEND_SMS, Manifest.permission.READ_CONTACTS}, 100);
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
requestPermissions(new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, 100);
}
// start the service
SensorService sensorService = new SensorService();
Intent intent = new Intent(this, sensorService.getClass());
if (!isMyServiceRunning(sensorService.getClass())) {
startService(intent);
}
button1 = findViewById(R.id.Button1);
listView = (ListView) findViewById(R.id.ListView);
db = new databaseOpenHelper(this);
list = db.getAllContacts();
customAdapter = new CustomAdapter(this, list);
listView.setAdapter(customAdapter);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calling of getContacts()
if (db.count() != 5) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
} else {
Toast.makeText(phone.this, "Can't Add more than 5 Contacts", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i("Service status", "Running");
return true;
}
}
Log.i("Service status", "Not running");
return false;
}
#Override
protected void onDestroy() {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, ReactivateService.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Permissions Denied!\n Can't use the App!", Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// get the contact from the PhoneBook of device
switch (requestCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
if (c.moveToFirst()) {
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String phone = null;
try {
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
phones.moveToFirst();
phone = phones.getString(phones.getColumnIndex("data1"));
}
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
db.addcontact(new ContactModel(0, name, phone));
list = db.getAllContacts();
customAdapter.refresh(list);
} catch (Exception ex) {
}
}
}
break;
}
}
}

BLUETOOTH_CONNECT permission

I have a problem, I try to activate Bluetooth but first I check for BLUETOOTH_CONNECT runtime permission (required by the BluetoothAdapter.enable()). Every time I request the permission is denied without displaying any dialog box, I tryed to request another permission and it works fine (displays dialog box with options - allow or denie) . I tryed to reinstall the app and clear its cache memory, i also checked for the app permissions allowed but i couldnt find Bluetooth. I also have the permissions in the Manifest.
public void enableordisableBT() {
if (MyBluetoothAdapter == null) {
Log.d(TAG,"Bluetooth not supported");
} else if (!MyBluetoothAdapter.isEnabled()) {
Log.d(TAG,"Bluetooth is currently not enabled");
if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "You have already granted this permission!", Toast.LENGTH_SHORT).show();
MyBluetoothAdapter.enable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
else
{
requestConnectPermission();
}
} else if (MyBluetoothAdapter.isEnabled()) {
MyBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
private void requestConnectPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.BLUETOOTH_CONNECT)) {
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_CONNECT}, CONNECTION_REQUEST_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_CONNECT}, CONNECTION_REQUEST_CODE);
Log.d(TAG," permisiune in curs de cerere ");
}
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CONNECTION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Permission Granted,access to connection available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Permission Denied, access to connection unavailable, app requires BLUETOOTH_CONNECT permission in order to operate", Toast.LENGTH_LONG).show();
}
break;
case SCAN_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(MainActivity.this, "Permission Granted,access to scan available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Permission Denied, access to scan unavailable, app requires BLUETOOTH_SCAN permission in order to operate", Toast.LENGTH_LONG).show();
}
break;
}
}

how do I make a call Directly when open my contact

the problem when I click on Button choose a contact and choose a contact not call the number, I want when choosing a Number phone call Directly
buttoncontact = findViewById(R.id.choosecontact);
public void choosecontact1 (View view){
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT)
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String call = buttoncontact.getText().toString();
if ((requestCode == 1) && (resultCode == RESULT_OK)) {
Cursor cursor = null;
try {
Uri uri = data.getData();
cursor = getContentResolver().query(uri, new String[] { ContactsContract.CommonDataKinds.Phone.NUMBER }, null, null, null);
if (cursor != null && cursor.moveToNext()) {
String phone = cursor.getString(0);
// the Problem on that code
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(String.valueOf("tel:" + CONTENT_TYPE)));
// i want open phone contact and call directly
if (ActivityCompat.checkSelfPermission(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(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
What is "CONTENT_TYPE"? Shouldn't it be the phone string you just get?
intent.setData(Uri.parse("tel:" + phone));
Add permission in manifest file :
Make function of calling phone number
private static final int CALL_REQUEST = 100;
private void callPhoneNumber(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(ProfileActivity.this, new String[]{Manifest.permission.CALL_PHONE}, CALL_REQUEST);
return;
}
}
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:9879879879" ));
startActivity(callIntent);
}
Above api level 23, need to ask runtime permission of call and if user allow it, it will go in below method :
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults)
{
if(requestCode == CALL_REQUEST)
{
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
callPhoneNumber();
}
else
{
Toast.makeText(ProfileActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}

After accept permission how to open a activity?

I trying to do a simple functionality. After the user accept permission for camera i need to open a new activity, but how do this?
This is a code. I check the permission and the request it. On my else if i open a new activity.
#RequiresApi(api = Build.VERSION_CODES.M)
#OnClick(R.id.scanButton)
void scanZxing(View view) {
if(getActivity().checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
Toast.makeText(context, "We need permissions to acces your CAMERA!", Toast.LENGTH_SHORT).show();
((MainActivity) context).checkCameraPermission();
} else if (view.getId() == R.id.scanButton) {
Intent intent = new Intent(getActivity(), ScanBarcodeActvity.class);
startActivityForResult(intent, 0);
}
}
#TargetApi(23)
public void checkCameraPermission(){
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M){
return;
}
if (this.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[] {Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
switch (requestCode) {
case REQUEST_CODE_CAMERA:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
} else {
Toast.makeText(this, "We need your permission to open camera",
LENGTH_SHORT).show();
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
You can check the permission request result in your activities onRequestPermissionsResult methodm and if user granted the permission then open the activity
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_CAMERA &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permisssion was granted
} else {
//permisssion was not granted
}
}
I am supposing you want to open ScanBarcodeActvity.
you can do it in following way
public void openScanBarCodeAcitvity() {
Intent intent = new Intent(getActivity(), ScanBarcodeActvity.class);
startActivityForResult(intent, 0);
}
Call above method at following place in addition to scanZxing() method
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[]
grantResults) {
switch (requestCode) {
case REQUEST_CODE_CAMERA:
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "Thanks for your permission", LENGTH_SHORT).show();
//permission granted, open activity
openScanBarCodeAcitvity();
} else {
Toast.makeText(this, "We need your permission to open camera",
LENGTH_SHORT).show();
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}

StartActivity once user click Allow on Permission Screen

My one activity need Location Permission and I wrote below code to get permission. But in this case user need to click twice to open activity if app does not have location permission initially. Can I make some change so that once user click allow on Permission screen, only then intent fires.
int PERMISSION_ALL = 1;
String[] PERMISSIONS = new String[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
PERMISSIONS = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION};
}
if (!hasPermissions(getApplicationContext(), PERMISSIONS)) {
ActivityCompat.requestPermissions(StartupActivity.this, PERMISSIONS, PERMISSION_ALL);
}
if (hasPermissions(getApplicationContext(), PERMISSIONS)) {
new Thread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(StartActivity.this, Details.class);
startActivity(intent);
}
}).start();
}
override onRequestPermissionsResult and if the permission is granted then start your Activity from there
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == PERMISSION_ALL){
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED ){
new Thread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(StartActivity.this, Details.class);
startActivity(intent);
}
}).start();
}else{
Toast.makeText(MainActivity.this, "Access Denied ! Cannot proceed further ", Toast.LENGTH_SHORT).show();
}
}
}
Note : Apparently , the code seems like in StartupActivity (from StartupActivity.this ) so you don't required to create a thread , simply start your Details Activity with simple Intent
Code will be
class StartupActivity extends ..{
onCreate...(){}
// here you will have onRequestPermissionsResult
#Override
public void onRequestPermissionsResult( ....){...}
}
Yes, you need to override onRequestPermissionsResult
First on onCreate
int PERMISSION_ALL = 1;
String[] PERMISSIONS = new String[0];
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
PERMISSIONS = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION};
}
if (!hasPermissions(getApplicationContext(), PERMISSIONS)) {
ActivityCompat.requestPermissions(StartupActivity.this, PERMISSIONS, PERMISSION_ALL);
}
then Override
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == PERMISSION_ALL) {
Intent intent = new Intent(StartActivity.this,Details.class);
startActivity(intent);
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{
// Handle your permission grant/reject scenarios here,
for( int x = 0; x < grantResults.length; x++ )
{
if( grantResults[x] == PackageManager.PERMISSION_GRANTED )
{
// Since you had one, start your new activity here
}
else
{
// Do something with the permissions that got BLOCKED??
}
}
}
This will be internally called by android, once user grants/rejects a permission

Categories

Resources