SMS Permissions - android

I am building an Android app via android studio. One major feature of the app is sending SMS but I cannot seem to get it to run correctly on different devices due to permission errors.I tried to eliminate this issue by prompting for permissions when the user logs in but this worked on API version 13 and failed on 26,I tried it with build.versioncode.o. but his also failed.
What is the correct way to do this and to check permissions each time a SMS is sent?(note sms are sent from many different functions throughout the app.
I also just got this error hen sending message
java.lang.SecurityException: Neither user 10205 nor current process has android.permission.READ_PHONE_STATE.
Request permission on log in
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void getPermissionToReadSMS() {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(
android.Manifest.permission.READ_SMS)) {
Toast.makeText(this, "Please allow permission!", Toast.LENGTH_SHORT).show();
}
requestPermissions(new String[]{android.Manifest.permission.READ_SMS},
REQUEST_READ_SMS);
}
}
Method snippet that sends method
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(testContact.getNumber(), null, "SENT MESSAGE" + message, sentPending, deliveredPending);
App Manifest
<!-- grant permission to uses in build sms service -->
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission-group.SMS" />

For checkPermission to send SMS, you will need to add
<uses-permission android:name="android.permission.SEND_SMS" />
permission and the below code for >=23 api
protected void sendSMS() {
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},
PERMISSION_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_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 successfully.",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild", Toast.LENGTH_LONG).show();
return;
}
}
}
}

//You should declare this in your project
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.READ_SMS,
Manifest.permission.RECEIVE_SMS,
Manifest.permission.SEND_SMS,
};
//and call verifymethod where you want
verifyStoragePermissions(Activity_home.this);
//and the verifyStoragePermissions methode is
public static void verifyStoragePermissions(Activity activity) {
int readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_PHONE_STATE);
int smspermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_SMS);
int smspermission1 = ActivityCompat.checkSelfPermission(activity, Manifest.permission.RECEIVE_SMS);
int smssendpermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.SEND_SMS);
if (readPermission != PackageManager.PERMISSION_GRANTED || readPermission != PackageManager.PERMISSION_GRANTED || smspermission != PackageManager.PERMISSION_GRANTED || smspermission1 != PackageManager.PERMISSION_GRANTED || smssendpermission != PackageManager.PERMISSION_GRANTED) {userActivityCompat.requestPermissions(activity,PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE );
}
}

I'm sending it from a fragment. The solution given by #Android Team above works for me for the first time only. Apparently if the app has required permission it doesnt call onRequestPermissionsResult.
Using the following code (else portion with log msg "Have permission.." in the onlclick handler is required for my app to work). I'm using Android 11 device.
if (ContextCompat.checkSelfPermission(getContext(),
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
//if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
if (shouldShowRequestPermissionRationale(
Manifest.permission.SEND_SMS)) {
} else {
//ActivityCompat.requestPermissions(getActivity(),
requestPermissions(
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
} else {
Log.i("smsB", "Have permission... send the sms now");
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
}

Related

SendTextMessage doesn't send SMS

I'm not getting any errors, but I don't see any SMS received on my phone either. My code:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(
this,
Manifest.permission.SEND_SMS
)
) {
// User has denied
} else {
ActivityCompat.requestPermissions(
this,
Array<String?>(10) { Manifest.permission.SEND_SMS }, MY_PERMISSIONS_REQUEST_SEND_SMS
)
}
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED) {
Log.d("TAG", "SENDING SMS!")
val number = "1234567890"
val message = "Verification message."
val sm: SmsManager = SmsManager.getDefault()
sm.sendTextMessage(number, null, message, null, null)
}
}
I do get the "SENDING SMS" logged in my console, so it means everything is ok regarding permissions, yet no SMS is being sent.
What could be the reason of the SMS not being sent?
P.S I'm using this random phone number "12345..", does it make any difference?
I'm so stupid, I thought the number should be the sender's number and it's just for displaying it, it has to be the receiver's number of course.

WifiManager.WifiInfo getSSID & getBSSID not working if targetSdkVersion >= 26

I'm getting correctly those values if I compile with API 27 but target API 25. If I set targetSdkVersion to 27, then, those values are not correctly retrieved.
Targeting SDK 25 or less, values are correct, but targeting 26 or more, I get those values:
SSID gives <unknown ssid>
BBSSID gives 02:00:00:00:00:00
These are my manifest permissions, all are normal permissions and don't require user grant:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And this is the sample code:
WifiManager wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo connectionInfo = wifiManager.getConnectionInfo();
connectionInfo.getSSID();
connectionInfo.getBSSID();
What has changed when targeting SDK 26 or more? what more should we do to get those values?
You need location permission starting with API 27
Google has changed their policy with WifiManager since you can track user's location tracking wifi location from SDK>=27. Therefore you need to access location permission in order to use getSSID() for your appliaction.
In order to use this code follow below.
As #Samuel Eminet answer above, you need either ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION. I used ACCESS_FINE_LOCATION because
ACCESS_COARSE_LOCATION request permission for only NETWORK_PROVIDE whereas
ACCESS_FINE_LOCATION request permissions for NETWORK_PROVIDE AND GPS_PROVIDER.
Refer here for more information
In your Manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
and where your wifi manager is, add this code to request permissions.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
//Permission Not Granted
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATION);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case PERMISSION_FINE_LOCATION:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted keep going status
Log.d(TAG, "PERMISSION GRANTED");
}
else {
Log.d(TAG, "PERMISSION DENIED");
}
}
}
One more thing to remember (I learned the hard way). If you are side-loading your app onto a device, don't forget to "allow" location permission in the app permissions (long press app, app info). It is off by default, thus you will get
I met with same problem. This problem happens higher android versions than API 23.
Solution:
You need to add below to build.gradle file.
implementation 'com.google.android.gms:play-services-location:15.0.0'
And you permission below rules.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
Below code provides automatically permission for location in application.
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
LocationRequest request = new LocationRequest()
.setFastestInterval(1500)
.setInterval(3000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
builder = new LocationSettingsRequest.Builder()
.addLocationRequest(request);
try {
Task<LocationSettingsResponse> result =
LocationServices.getSettingsClient(this.getApplicationContext()).checkLocationSettings(builder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try {
task.getResult(ApiException.class);
} catch (ApiException e) {
switch (e.getStatusCode()) {
case LocationSettingsStatusCodes
.RESOLUTION_REQUIRED:
ResolvableApiException resolveApiException = (ResolvableApiException) e;
try {
resolveApiException.startResolutionForResult(WifiConnectionActivity.this, REQUEST_CHECK_CODE);
} catch (IntentSender.SendIntentException ex) {
ex.printStackTrace();
} catch (ClassCastException ex) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
}
});
} catch (Exception x) {
}
checkPermissions();
} catch (Exception a) {
}
}
void checkPermissions() {
if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(WifiConnectionActivity.this, new String[]
{
Manifest.permission.ACCESS_COARSE_LOCATION
}, REQUEST_LOCATION);
}
else{
//Toast.makeText(getActivity(), "GPS is already permissioned", Toast.LENGTH_SHORT).show();
}
}
The below is the code .
public String getMac() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//Permission Not Granted
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}else{
WifiManager wifimanage = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiinfo = wifimanage.getConnectionInfo();
macAddress = wifiinfo.getBSSID();//Get the mac address of the currently connected network;
}
return macAddress;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//permission granted keep going status
Log.d("mac", "PERMISSION GRANTED");
WifiManager wifimanage = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiinfo = wifimanage.getConnectionInfo();
macAddress = wifiinfo.getBSSID();//Get the mac address of the currently connected network;
} else {
Log.d("mac", "PERMISSION DENIED");
}
}
}
Then call getMac() to solve the problem.

internet permission not granted

I am writing an app to send msg over TCP Socket. I am struggling to get access to the internet permission. (API 26 is the target)
socket EACCESS permission denied
I have setup in my Manfest :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.seb.sebastien.opengardenirc">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.persmission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
As I am using the API26, I have to add a permission check in the code to make sure it works fine:
if (shouldAskPermission()) {
Log.d(TAG, "Permission is required");
String[] PERMISSIONS_STORAGE = {
Manifest.permission.ACCESS_NETWORK_STATE,
Manifest.permission.INTERNET,
Manifest.permission.ACCESS_WIFI_STATE
};
int permission_internet = ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET);
int permission_network = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_NETWORK_STATE);
int permission_wifi = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE);
Log.d(TAG, "Package Manager: " + PackageManager.PERMISSION_GRANTED);
Log.d(TAG, "INTERNET : " + permission_internet);
Log.d(TAG, "NETWORK : " + permission_network);
Log.d(TAG, "WIFI : " + permission_wifi);
if ((permission_internet != PackageManager.PERMISSION_GRANTED)
|| (permission_network != PackageManager.PERMISSION_GRANTED)
|| (permission_wifi != PackageManager.PERMISSION_GRANTED)){
Log.d(TAG, "Asking for permission");
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
this,
PERMISSIONS_STORAGE,
REQUEST_CONNECTION_PERMISSION
);
} else {
Toast.makeText(MainActivity.this, "Permission (already) Granted!", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Permission already granted");
startTcpInAThread("str");
}
}
And I have also the method to catch the onRequestPermissionsResult.
private boolean shouldAskPermission(){
return(Build.VERSION.SDK_INT> Build.VERSION_CODES.LOLLIPOP_MR1);
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){
switch(permsRequestCode){
case REQUEST_CONNECTION_PERMISSION:
Log.d(TAG, "Permission granted result : " + grantResults[0]);
Log.d(TAG, "Permission granted result : " + grantResults[1]);
Log.d(TAG, "Permission granted result : " + grantResults[2]);
boolean accepted = (grantResults[0]== PackageManager.PERMISSION_GRANTED)
&& (grantResults[1]== PackageManager.PERMISSION_GRANTED)
&& (grantResults[2]== PackageManager.PERMISSION_GRANTED);
if(accepted) {
startTcpInAThread("str");
} else {
Toast.makeText(getApplicationContext(), "Permissions issues!!!!", Toast.LENGTH_SHORT).show();
}
break;
}
}
First things is that when checking the permission, I can see that android.persmission.INTERNETis not granted. Good thing is that it's going to call the request permission method ActivityCompat.requestPermissions
I was expecting a Dialog box showing up but my understanding is that the dlgbox only show up for some on the permission requests some other do not need to ask.
My concerns is that when I got onRequestPermissionsResultthe permission is still not granted.
Anybody know how to grant the permission to internet ?
I have also pay attention to not run the network access in the same thread.
Regards

after build app, connection error on android marshmallow

my device on android marshmallow.
so I use get permission this method.
int currentApiVer = Build.VERSION.SDK_INT;
Log.d(TAG, "currentApiVer = " + currentApiVer);
if (currentApiVer >= Build.VERSION_CODES.M) {
Log.d(TAG, "currentApiVer ----------------------------");
verifyPermissions(this);
} //onCreate()
private static boolean verifyPermissions(AppCompatActivity activity) {
Log.d(TAG, "verifyPermissions --------------------------------------");
int writePerm = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int readPerm = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
int camera_perm = ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
if (writePerm != PackageManager.PERMISSION_GRANTED ||
readPerm != PackageManager.PERMISSION_GRANTED ||
camera_perm != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
activity, PERMISSIONS_REQ, REQUEST_CODE_PERMISSIONS
);
return false;
} else {
return true;
}
}
my app is CCTV app. I use WebRTC
my problem when I first build my app.
show permission dialog. when I check permit permission.
success CCTV connect.
but I try again start built app.
fail CCTV connect.
clearly I already check permit permission.
perhaps, I think marshmallow permission problem.
in this situation. how I fix this problem?
thanks.

Is there a way to get all permission granted to an application [duplicate]

I want to get all granted permissions. I know I can get all requested permissions by packageinfo.requestedPermissions but I want to know list of granted permissions and granted permissions can be lesser then requested in case of android M. So I just wanted to know that is there way that I can get list of all granted permissions?
I know from list of requested permission I can check for that permission weather granted or not but I want to know list of all granted permission. Don't want to check for every requested permission.
A simple function that returns all the permissions that have been requested and granted for a given package could look like this:
List<String> getGrantedPermissions(final String appPackage) {
List<String> granted = new ArrayList<String>();
try {
PackageInfo pi = getPackageManager().getPackageInfo(appPackage, PackageManager.GET_PERMISSIONS);
for (int i = 0; i < pi.requestedPermissions.length; i++) {
if ((pi.requestedPermissionsFlags[i] & PackageInfo.REQUESTED_PERMISSION_GRANTED) != 0) {
granted.add(pi.requestedPermissions[i]);
}
}
} catch (Exception e) {
}
return granted;
}
Note that this requires API level 16 or above, but that should hopefully not be an issue these days.
You can check permission one by one and add to list:
// Should we show an explanation?
List<String> listPermissionsNeeded = new ArrayList<>();
// No explanation needed, we can request the permission.
if((ContextCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED))
{
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if((ContextCompat.checkSelfPermission(context,
Manifest.permission.GET_ACCOUNTS)
!= PackageManager.PERMISSION_GRANTED))
{
listPermissionsNeeded.add(Manifest.permission.GET_ACCOUNTS);
}
if((ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED))
{
listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if((ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED))
{
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if((ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED))
{
listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(context,
listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),
MY_PERMISSIONS_REQUEST_MULTIPLE_PERMISSION);
}

Categories

Resources