hi i am using this code to send sms on any number but it is working for the first time and there is no next time. any fix? is there a problem in MY_PERMISSION_REQUEST_SEND_SMS? Is there any other short method to send sms?
protected void SendSms() {
phonenumber=number.getText().toString();
message= txt.getText().toString();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[],
int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phonenumber, null, message, null,
null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
return;
}
}
}
You don't have the condition when you already have the access to Send SmS permission
Put else for outer if and execute your send sms code
This is because you missed to call smsManager send sms if permission granted
Better make a method,
private void smsSend(){
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phonenumber, null, message, null,
null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
}
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
else{
smsSend(); //call method if already granted
}
and call this method after permission granted also,
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[],
int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
smsSend(); //call method after permission grant
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
return;
}
}
}
}
Related
how do i make it so that when the user accepts location permission it will start working and no need to restart the app. At first on launch, my app will request location permission from the user, but even after they accept it will not run properly using these permissions. It will only work properly after restarting the app.
private void getLocationPermission() {
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = true;
Log.d(TAG, "GRANTED");
initMap();
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionsGranted) {
#SuppressLint("MissingPermission") final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFUALT_ZOOM,
"My Location");
} else {
Log.d(TAG, "onCOmplete: current location is null");
}
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "getDeviceLocation: Security Exception: " + e.getMessage());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
mLocationPermissionsGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
mLocationPermissionsGranted = true;
Log.d(TAG, "onRequestPermissionsResult: permission granted");
initMap();
}
}
}
}
I am trying to request 2 permissions when the app opens up. It works fine, but when the user selects never ask again, a toast message should be displayed once. The toast message keeps on coming up repeatedly and does not stop. I cannot figure out the reason for this.
public void checkPermission(final Context context) {
if(ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Both permissions granted", Toast.LENGTH_SHORT).show();
} else {
checkPermission(this);
}
if (requestCode == 1) {
for (int i = 0, len = permissions.length; i < len; i++) {
String permission = permissions[i];
boolean showRationale;
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
showRationale = shouldShowRequestPermissionRationale(permission);
if (!showRationale) {
Toast.makeText(this, "Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
}
Above is the code that checks for permissions.
I would like to know why the toast message never stops popping up.
Try following code -
public class MainActivity extends AppCompatActivity{
private static final int STORAGE_PERMISSION_REQ_CODE = 1001;
private static final int CAMERA_PERMISSION_REQ_CODE = 1002;
private static final int BOTH_PERMISSION_REQ_CODE = 1003;
...........
private void checkPermission(){
if(hasBothPermission()){
// Has both permission
}
else if(hasReadStoragePermission(READ_EXTERNAL_STORAGE))
// Has Storage Permission request Camera Permission
requestPermissions(new String[]{CAMERA}, CAMERA_PERMISSION_REQ_CODE);
else if(hasCameraPermission(CAMERA))
// Has Camera Permission request Storage Permission
requestPermissions(new String[]{READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_REQ_CODE);
else
// Request Both Permission
requestPermissions(new String[]{READ_EXTERNAL_STORAGE, CAMERA},BOTH_PERMISSION_REQ_CODE);
}
private boolean hasBothPermission(){
return (ContextCompat.checkSelfPermission(this, CAMERA) == PackageManager.PERMISSION_GRANTED) &&
ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
}
private boolean hasCameraPermission(String perm) {
return (ContextCompat.checkSelfPermission(this, perm) == PackageManager.PERMISSION_GRANTED);
}
private boolean hasReadStoragePermission(String perm) {
return (ContextCompat.checkSelfPermission(this, perm) == PackageManager.PERMISSION_GRANTED);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == STORAGE_PERMISSION_REQ_CODE){
if(hasReadStoragePermission(READ_EXTERNAL_STORAGE))
Toast.makeText(this, "Storage Permission Granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Storage Permission Failed, Request Again", Toast.LENGTH_SHORT).show();
}
else if(requestCode == CAMERA_PERMISSION_REQ_CODE){
if(hasCameraPermission(CAMERA))
Toast.makeText(this, "Camera Permission Granted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Camera Permission Failed, Request Again", Toast.LENGTH_SHORT).show();
}
else {
if(hasBothPermission())
Toast.makeText(this, "Permission Granted Success", Toast.LENGTH_SHORT).show();
else
Toast.makeText(this, "Permission Failed Request Permission Again", Toast.LENGTH_SHORT).show();
}
}
...........
}
I'm having difficulties in sending my location coordinates via SMS. I can't frame the sending SMS correctly. Here is my top code:
private static final int REQUEST_CODE = 1000;
FusedLocationProviderClient fusedLocationProviderClient;
LocationRequest locationRequest;
LocationCallback locationCallback;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode)
{
case REQUEST_CODE:
{
if(grantResults.length > 0)
{
if(grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
}
else if(grantResults[0] == PackageManager.PERMISSION_DENIED)
{
}
}
}
}
}
Here in my onCreate the double && sign reads an unexpected token error. I also think I need to add a private void there but don't know which kind corresponds with sending an SMS.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION))
{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
}
else
{
buildLocationRequest();
buildLocationCallback();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
{
if (ActivityCompat.checkSelfPermission(FullscreenActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
&& ActivityCompat.checkSelfPermission(FullscreenActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
ActivityCompat.requestPermissions(FullscreenActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
FusedLocationProviderClient provider = fusedLocationProviderClient;
Location currentLocation = new Location(String.valueOf(provider));
location("MY_PHONE_NUMBER", currentLocation);
After the onCreate section is where I'm having the most dificulties at particularly with the location method at the Location currentLocation string which says parameter is never used and I also get an error with the getLongitude closing. It contains an error with the semi-colon and nothing I add there works such as a ). I don't know if I'm doing this location/SMS class correctly.
private void location(String phoneNumber, Location currentLocation) {
SmsManager smsManager = SmsManager.getDefault();
String smsBody = "maps.google.com?q=";
smsManager.sendTextMessage(phoneNumber, null, smsBody, null, null);
}
private void buildLocationCallback() {
locationCallback = new LocationCallback()
{
#Override
public void onLocationResult(LocationResult locationResult) {
for(Location location:locationResult.getLocations())
SmsManager.getDefault(String.valueOf(location.getLatitude())
+","
+String.valueOf(location.getLongitude());
}
};
}
private void buildLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(100);
locationRequest.setFastestInterval(50);
locationRequest.setSmallestDisplacement(10);
}
Add getLastLocation() method after buildLocationCallback
private void getLastLocation() {
try {
fusedLocationProviderClient.getLastLocation()
.addOnCompleteListener(new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mLocation = task.getResult();
location("MY_PHONE_NUMBER", task.getResult());
} else {
Log.w(TAG, "Failed to get location.");
}
}
});
} catch (SecurityException unlikely) {
Log.e(TAG, "Lost location permission." + unlikely);
}
}
update your location method
private void location(String phoneNumber, Location currentLocation) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, "maps.google.com?q=" + currentLocation.getLatitude() + "," + currentLocation.getLongitude(), null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
I'm trying to get access to the system settings, but it seems my method that requests the permission always returns false. My knowledge is limited so I don't really know where to start to fix it
private void getPermissions(){
boolean value;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
value = Settings.System.canWrite(getApplicationContext());
if(value) {
success = true;
}else{
Intent intent = new
Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
intent.setData(Uri.parse("package:" +
getApplicationContext().getPackageName()));
startActivity(intent);
}
}
}
the getPermission() is called upon the creation of the app.
Try this
String[] permissionsRequired = new String{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.RECORD_AUDIO};
//on button click
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if ((ContextCompat.checkSelfPermission(this, permissionsRequired[0])
!= PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, permissionsRequired[1])
!= PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(this, permissionsRequired[2])
!= PackageManager.PERMISSION_GRANTED)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermission();
}
}
}
}
break;
}
}
public void requestPermission() {
ActivityCompat.requestPermissions((Activity) this, permissionsRequired, REQUEST_PERMISSION_SETTING);
}
I am trying a basic program for sending SMS from android app. But now when I run the app, nothing happens after clicking send sms button. I see no error message.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[]
permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
//return;
}
}
}
}
Read about onRequestPermissionsResult()
You need to pass NonNull parameters in onRequestPermissionsResult()
Parameters
requestCode int: The request code passed in
permissions String: The requested permissions. Never null.
grantResults int: The grant results for the corresponding permissions which is either PERMISSION_GRANTED or PERMISSION_DENIED. Never null.
SAMPLE CODE
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
//return;
}
}
}
}