when I use this code, first comes the dial pad screen with this number.
Intent dialintnt = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:911"));
startActivityForResult(dialintnt, CALLING);
I don't want that screen. I want that when I click button directly calling that number.
So how can I call a number onclick?
It's not possible. This is for user protection.
It's been a long time. But may help someone else.
If you want to call directly, you should use requestPermissions method.
1. Add this line to your manifest file:
<uses-permission android:name="android.permission.CALL_PHONE" />
2. Define a class variable in the activity class:
private static Intent phoneCallIntent; //If use don't need a member variable is good to use a static variable for memory performance.
3. Add these lines to the onCreate method of the activity:
final String permissionToCall = Manifest.permission.CALL_PHONE;
//Assume that you have a phone icon.
(findViewById(R.id.menuBarPhone)).setOnClickListener(new OnClickListener(){
public void onClick(View view) {
phoneCallIntent = new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(getString(R.string.callNumber))); //Uri.parse("tel:your number")
if (ActivityCompat.checkSelfPermission(MainFrame.this, permissionToCall) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainFrame.this, new String[]{permissionToCall}, 1);
return;
}
startActivity(phoneCallIntent);
}
});
4. And for making a call immediately after clicking on Allow button, override onRequestPermissionsResult method:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults){
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 1){
final int permissionsLength = permissions.length;
for (int i = 0; i < permissionsLength; i++) {
if(grantResults[i] == PackageManager.PERMISSION_GRANTED){
startActivity(phoneCallIntent);
}
}
}
When a user give the permission, next time there will be no dialogue box and call will be make directly.
See the answer
You will need add CALL_PHONE and CALL_PRIVILEGED permissions to manifest file.
Then the number can be called using:
Uri callUri = Uri.parse("tel://911");
Intent callIntent = new Intent(Intent.ACTION_CALL,callUri);
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_USER_ACTION);
startActivity(callIntent);
Just change ACTION_DIAL to ACTION_CALL. Like this:
Intent dialintnt = new Intent(Intent.ACTION_CALL,Uri.parse("tel:911"));
startActivityForResult(dialintnt, CALLING);
Try this:
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" +phone_number));
startActivity(callIntent);
Number has to be proper formatted as if you try with country code it will take you default dailer. i tested it on my app when i am using number as 198 call is happening directly and when i am using 9999999999 this will invoke the dailer so that user can correct the number by adding country code.
`val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:+91987654310" ))
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)`
Related
I really have no idea how to do it like this, the note is able to attach photo from camera and gallery
Also the other functions like shown on the upper part, I haven't found any tutorial about it. I need help, thank you. I'm a beginner
The scope of this problem may be a bit broad, but I'll try to summarize it as best as I can.
In order to render images from say, a user's third-party gallery app, you'd need to access their device storage first by initially setting the storage permission in your manifest as follows:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Next, you have to address granting permissions (accessing the user's device storage is considered a dangerous permission) accordingly for Android 6.0/Marshmallow and above at runtime (during installation for Android 6.0 and below) prior to running any UI threads as mentioned here in the docs. Then you open up the gallery app from say, clicking on a Button, and then render an ImageView with bitmap to the URI path of the selected image by using the storage data via a Cursor all within onActivityResult().
Here's a sample Activity of just that:
public class MainActivity extends AppCompatActivity {
// Constant that's used as a parameter to assist with the permission requesting process.
private static final int PERMISSION_CODE = 100;
// Int constant that's used to handle the result back when an image is selected from the
// device's gallery.
private static final int RESULT_LOAD_IMAGE = 1;
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Requests permission for devices with versions Marshmallow (M)/API 23 or above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_CODE);
return;
}
}
// The following invoking method either executes for versions older than M, or until the
// user accepts the in-app permission for the next sessions.
runUi();
}
// Displays a permission dialog when requested for devices M and above.
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == PERMISSION_CODE) {
// User accepts the permission(s).
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Invoker for rendering UI.
runUi();
} else { // User denies the permission.
Toast.makeText(this, "Please come back and then grant permissions!",
Toast.LENGTH_SHORT).show();
// Runs a thread for a slight delay prior to shutting down the app.
Thread mthread = new Thread() {
#Override
public void run() {
try {
sleep(1500);
System.exit(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
mthread.start();
}
}
}
private void runUi() {
mImageView = (ImageView) findViewById(R.id.image_view);
// Sets the image button clickable with the following functionality.
findViewById(R.id.change_img_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Instantiates an Intent object for accessing the device's storage.
Intent intent = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Triggers the image gallery.
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
});
}
/**
* Invoked once a third-party app (such as Gallery) is dismissed from its purpose via an
* implicit intent.
*
* #param requestCode is the code constant of the intent's purpose.
* #param resultCode is the result code constant of the intent.
* #param data is the actual intent.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Runs the following code should the code constants and intent match that of selecting an
// image from the device's gallery.
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
// References the device's storage URI for images from the intent parameter.
Uri selectedImageUri = data.getData();
// Initializes a temporary string list of the image file path as the column to render
// the image immediately.
String[] projection = { MediaStore.Images.Media.DATA };
// References and queries the database with the following parameters, and then moves to
// the first row index.
Cursor cursor = getContentResolver().query(
selectedImageUri, // Provider content URI to query
projection, // Columns to include in the resulting Cursor
null, // No selection clause
null, // No selection arguments
null); // Default sort order
cursor.moveToFirst();
// Retrieves and assigns the file path as a string value, and then sets the image's
// bitmap to render it.
String imgFilePath = cursor.getString(cursor.getColumnIndex(projection[0]));
mImageView.setImageBitmap(BitmapFactory.decodeFile(imgFilePath));
// Closes the cursor to release all of its resources.
cursor.close();
}
}
}
Hi I'm Using Easy Permission library to handle android 6+ permission.
There is a method to call when "never ask again" is check
EasyPermissions.checkDeniedPermissionsNeverAskAgain
I dont know what parameter should we pass to the method
This is the method definition
public static boolean checkDeniedPermissionsNeverAskAgain(final Object object,
String rationale,
#StringRes int positiveButton,
#StringRes int negativeButton,
#Nullable DialogInterface.OnClickListener negativeButtonOnClickListener,
List<String> deniedPerms) {
boolean shouldShowRationale;
for (String perm : deniedPerms) {
shouldShowRationale = shouldShowRequestPermissionRationale(object, perm);
if (!shouldShowRationale) {
final Activity activity = getActivity(object);
if (null == activity) {
return true;
}
AlertDialog dialog = new AlertDialog.Builder(activity)
.setMessage(rationale)
.setPositiveButton(positiveButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
startAppSettingsScreen(object, intent);
}
})
.setNegativeButton(negativeButton, negativeButtonOnClickListener)
.create();
dialog.show();
return true;
}
}
return false;
}
But how to we pass the Stringres. Any help is much appreciate. Thanks
It just wants a resource value from your strings.xml file. So just pass something like R.string.okay and R.string.cancel. If you don't have a strings.xml file setup (you probably should) but could also use system defaults and pass android.R.string.ok and android.R.string.cancel to that method. There are several built in system strings like that. Look here if you're curious.
In my android app I want to change the input method. So I start a new Activity which shows the language settings in the device. Then user can change it. However then I want to know that if the user has changed it. So I wrote a function for that also. My code so far is...
Intent enableIME = new Intent(android.provider.Settings.ACTION_INPUT_METHOD_SETTINGS);
startActivityForResult(enableIME,0);
if(isInputMethodEnabled()){
activateshadow.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_pressed));
activateshadow.setText("Deactivate Shadow");
prefs.edit().putBoolean("Activate", false).commit();
}else{
Toast.makeText(MainActivity.this,"You haven't change the input method to simpleIME.In order to activate you must change it.",Toast.LENGTH_SHORT).show();
}
my is inputMethodEnabled function is....
public boolean isInputMethodEnabled() {
boolean isIME ;
String id = Settings.Secure.getString(getApplicationContext().getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);
String [] name = id.split("/.");
// Toast.makeText(MainActivity.this,"s:"+name[1]+":s",Toast.LENGTH_SHORT).show();
if(name[1].contains("SimpleIME") ){
isIME = true ;
}else{
isIME = false;
}
// Toast.makeText(MainActivity.this,"Returning..."+isIME,Toast.LENGTH_SHORT).show();
return isIME;
}
if(isInputMethodEnabled()) always fails because when the new intent(settings) opens and it take some time to change the input method to simpleIME . How to fix this problem?
You catch when a launched Activity returns in onActivityResult. The requestCode you supplied to startActivityForResult will be a parameter, as will the Activity's result. The Activity may also set other data which you didn't ask about.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 555) {//555 is the intent ID you gave in startActivityForResult(enableIME,555);
if (resultCode == /*Result1*/)
//Do something
else {
//Do something else
}
}
}
You need a unique id when calling startActivityForResult(enableIME,0);
startActivityForResult(enableIME, 555);
Better still replace 555 with a named variable.
if u look at android life cycle, when activity is finished whole android call onDestroy() method.
so u can call and override this method.
just need write:
#override
protected void onDestroy(){
// code
super.onDestroy();
}
u can manage and override all of life cycle's parts in android
e.g: onResume to get current activity
i hope this help u
Because the Android SDK 23 gives users the possibility to deny apps access to certain functionalities I wanted to update one of my apps to request permissions as it is described in here: https://developer.android.com/preview/features/runtime-permissions.html.
In one of the activities I embed a SupportMapFragment. To make it work you need to have the WRITE_EXTERNAL_STORAGE permission, so I request it when I start the activity which results in a creation of a permission request dialog.
Now the problem is that when the dialog is still open and I rotate the device the activity will be restarted and open a new permission request dialog while the old one is still there. The result is two of those dialogs on top of each other and only one of it being useful.
Is there a way to get rid of the dialog that was started first?
As CommonsWare said in his comment the best solution is to put a boolean into the savedInstanceState-Bundle to know if the dialog is still open.
Example:
// true if dialog already open
private boolean alreadyAskedForStoragePermission = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null) {
alreadyAskedForStoragePermission = savedInstanceState.getBoolean(STORAGE_PERMISSION_DIALOG_OPEN_KEY, false);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY, alreadyAskedForStoragePermission);
}
private void checkStoragePermission(){
if(alreadyAskedForStoragePermission){
// don't check again because the dialog is still open
return;
}
if(ActivityCompat.checkSelfPermission(this, STORAGE_PERMISSIONS[0]) != PackageManager.PERMISSION_GRANTED){
// the dialog will be opened so we have to keep that in memory
alreadyAskedForStoragePermission = true;
ActivityCompat.requestPermissions(this, STORAGE_PERMISSIONS, STORAGE_PERMISSION_REQUEST_CODE);
} else {
onStoragePermissionGranted();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case STORAGE_PERMISSION_REQUEST_CODE:
// the request returned a result so the dialog is closed
alreadyAskedForStoragePermission = false;
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
onStoragePermissionGranted();
}
break;
}
}
As #user1991776 mentioned there is actually an undocumented extra that contains whether or not there is a permission dialog open at the moment, in Activity:
private static final String HAS_CURENT_PERMISSIONS_REQUEST_KEY =
"android:hasCurrentPermissionsRequest";
However there is a better way. When you request a permission dialog the second time (due to a rotation), Activity automatically cancels the old dialog by calling your onRequestPermissionResult() with empty arrays:
public final void requestPermissions(#NonNull String[] permissions, int requestCode) {
if (mHasCurrentPermissionsRequest) {
Log.w(TAG, "Can reqeust only one set of permissions at a time");
// Dispatch the callback with empty arrays which means a cancellation.
onRequestPermissionsResult(requestCode, new String[0], new int[0]);
return;
}
Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
mHasCurrentPermissionsRequest = true;
}
Or course this behaviour isn't documented because this is Android, and who wants to document complex behaviour?
Anyway you can just always request permissions in onCreate() and then ignore calls to onRequestPermissionsResult() with zero-length permissions arrays.
I guess as this is a system dialog you cannot control it. You could instead prevent that your activity gets reloaded if you turn your device.
I know it was very simple to do it but I come across a very strange issue. I have to call Police in danger Situation by just tapping a button. So I have used following code to call.
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:100"));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(callIntent);
Added CALL_PHONE permission in AndroidManifest.xml. The Issue is that it is opening the 100 on Dial Pad but not making call directly. I want that to happen immediately when user clicks on the button.
When I tried to to put +91 before 100 it is calling the number automatically but why plus is required for such numbers. So Someone help me how to solve this issue
From the documentation of ACTION_CALL:
Note: there will be restrictions on which applications can initiate a call; most applications should use the ACTION_DIAL.
Note: this Intent cannot be used to call emergency numbers. Applications can dial emergency numbers using ACTION_DIAL, however.
So it seems this behavior is on purpose.
There could be a problem that the android system doesnt recognize 100 as a valid phone number, instead if you put the country code before it then it works fine. TO solve such issue take a look at this library libnhonenumber. You could use it something like this
public static ArrayList<String> extractPhoneNumber(String content) {
ArrayList<String> numbers = new ArrayList<String>(0);
PhoneNumberUtil instance = PhoneNumberUtil.getInstance();
//Change IT with your contry code
Iterable<PhoneNumberMatch> matches = instance.findNumbers(content, "IT");
Iterator<PhoneNumberMatch> iterator = matches.iterator();
while (iterator.hasNext()) {
numbers.add(instance.format(iterator.next().number(), PhoneNumberFormat.INTERNATIONAL));
}
return numbers;
}
private void phoneCall()
{
String phoneCallUri = "tel:91";
Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(phoneCallUri));
startActivity(phoneCallIntent);
}
Best way to directly call without user intervention..
String uri = "tel:" + num.trim();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);
There are two intents to call/start calling: ACTION_CALL and ACTION_DIAL.
ACTION_DIAL will only open the dialer with the number filled in, but allows the user to actually call or reject the call. ACTION_CALL will immediately call the number and requires an extra permission.
So make sure you have the permission
A Long time passed. But may help someone else.
If you want to call directly, you should use requestPermissions method.
1. Add this line to your manifest file:
<uses-permission android:name="android.permission.CALL_PHONE" />
2. Define a class variable in the activity class:
private static Intent phoneCallIntent; //If use don't need a member variable is good to use a static variable for memory performance.
3. Add these lines to the onCreate method of the activity:
final String permissionToCall = Manifest.permission.CALL_PHONE;
//Assume that you have a phone icon.
(findViewById(R.id.menuBarPhone)).setOnClickListener(new OnClickListener(){
public void onClick(View view) {
phoneCallIntent = new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(getString(R.string.callNumber))); //Uri.parse("tel:your number")
if (ActivityCompat.checkSelfPermission(MainFrame.this, permissionToCall) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainFrame.this, new String[]{permissionToCall}, 1);
return;
}
startActivity(phoneCallIntent);
}
});
4. And for making a call immediately after clicking on Allow button, override onRequestPermissionsResult method:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults){
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 1){
final int permissionsLength = permissions.length;
for (int i = 0; i < permissionsLength; i++) {
if(grantResults[i] == PackageManager.PERMISSION_GRANTED){
startActivity(phoneCallIntent);
}
}
}
When a user give the permission, next time there will be no dialogue box and call will be make directly.