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();
}
}
}
Related
I was trying to select an image from a device folder but it an error in the logcat like this:
(https://i.stack.imgur.com/0yFm8.jpg)
(https://i.stack.imgur.com/owWL4.jpg)
This error doesn't always come out and sometimes it changes, but it's always about running out of memory
This is the code with which I choose an image in the gallery:
public void inserimentoImmagine() {
addImage = findViewById(R.id.aggiuntaFoto);
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (ActivityCompat.checkSelfPermission(AggiuntaAnimaleManuale.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AggiuntaAnimaleManuale.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PICK_FROM_GALLERY);
} else {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PICK_FROM_GALLERY:
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
} else {
//do something like displaying a message that he didn`t allow the app to access gallery and you wont be able to let him select from gallery
}
break;
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
if (data == null) {
//Display an error
return;
}
Uri imgUri= data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor=getContentResolver().query(
imgUri, filePathColumn, null, null, null
);
String picturePath;
Bitmap bitmap;
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
bitmap = BitmapFactory.decodeFile(picturePath);
image.setImageBitmap(bitmap);
}
}
}
}
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;
}
}
}
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);
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
I am trying to ask users to select their google account here. After I use the "setSelectedAccoutName" method, i try to print out the selected account name which returns null. I am 100% sure that accountName is not null. So does anyone know why mCredential.getSelectedAccountName is null?
private void pickContact() {
AccountManager accountManager = AccountManager.get(getActivity().getApplicationContext());
Account[] accounts = accountManager.getAccountsByType(null);
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
new String[]{"com.google"},
false, null, null, null, null);
startActivityForResult(intent, 23);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("hi");
if (requestCode == 23) {
if (resultCode == Activity.RESULT_OK) {
Bundle bundle = data.getExtras();
String accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
System.out.println(accountName);
if (accountName != null) {
mCredential.setSelectedAccountName(accountName);
System.out.println(mCredential.getSelectedAccountName());
getResultsFromApi();
} else {
pickContact();
}
}
}
}