I am trying to code a quick application which gives me the needed 3G values, when I click a button.
But first I need to check if I am connected to 3G network.
However I am having some issues with my Permissions.
I am having the following code:
public void calculate(View view) {
TextView rscp = (TextView) findViewById(R.id.RSCP);
TextView rssi = (TextView) findViewById(R.id.RSSI);
TextView ecno = (TextView) findViewById(R.id.EcNo);
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (Arrays.stream(values_3G).anyMatch(n -> n == tm.getDataNetworkType())) {
for (CellInfo cellInfo : tm.getAllCellInfo()) {
if (cellInfo instanceof CellInfoWcdma) {
CellSignalStrengthWcdma cellSignalStrength = ((CellInfoWcdma) cellInfo).getCellSignalStrength();
rscp.setText(cellSignalStrength.getDbm());
ecno.setText(cellSignalStrength.getEcNo());
int rssiValue = -113 + 2 * cellSignalStrength.getAsuLevel();
rssi.setText(rssiValue);
}
}
} else {
rscp.setText(0);
rssi.setText(0);
ecno.setText(0);
Log.i(TAG, "No 3G Mobile connection detected!");
Toast.makeText(getApplicationContext(), "Connect to 3G", Toast.LENGTH_SHORT).show();
}
}
tm.getDataNetworkType() is giving me the following issue with READ_PHONE_STATE:
Call requires permission which may be rejected by user: code should explicitly check to see if permission is available (with checkPermission) or explicitly handle a potential SecurityException
If I follow the instructions to check permission in Android Studio I get the following:
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != 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;
}
What do I need to fill in between the brackets?
Create a global final int of the permission request code
final int PHONE_REQUEST_CODE = 101;
And request the permission if not granted
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
PHONE_REQUEST_CODE); // triggers onRequestPermissionsResult()
} else {
// calculate(myView); // Do whatever you want as the permission is already granted
}
And override onRequestPermissionsResult() in activity
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults.length == 0)
return;
if (requestCode == PHONE_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// calculate(myView); // Do whatever you want after the permission is granted
}
And add the permission in manifest.xml as well.
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Related
Any idea how to enable the permission on the app? the permission was disabled by default on Android 13 Emulator. It was working on other emulator, just not Android 13 Emulator. By default, adding Firebase Messaging will add the Manifest.permission.POST_NOTIFICATIONS into the Manifest.
requestPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS);
auto return isGranted = false
in Manifest:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
This is how to request and check results for runtime for api13
private void request_notification_api13_permission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
if (this.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.POST_NOTIFICATIONS}, 22);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 22) {
if (grantResults.length > 0)
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted, perform required code
} else {
// not granted
}
}
}
calling function will be like this:
request_notification_api13_permission();
I cannot make this work, I have an application with a webview that requires permissions to access storage when downloading, I am trying that, when the user rejects permissions, my application tells them how to activate the permission by accessing the application settings.
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.fromParts("package", getActivity().getPackageName(), null));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivityForResult(intent, MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
s
#Override
public void onRequestPermissionsResult(int requestCode,
String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Permission is granted
myWebView.loadUrl(urlDownload);
} else {
}
return;
}
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openImageChooserActivity();
} else {
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}
myWebView.loadUrl(urlDownload); this code snippet runs without problem when permission is granted from android alert but I can't control it if the user grants the permission from the settings.
Finally, a newbie question, I have seen several examples of similar codes that seem to work, but I do not understand how setResult is handled in the configurations because I do not have access to it, if for example MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 101 how is it that android configurations know to put setResult (101) when user activates storage?
I'm using telephony manager to identify the phone number that has been inputted in the edit text. How to identify if the phone number inputted is the number that is currently being used in the android device?
public void initlogin(String phonenumber) {
TelephonyManager tMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != 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;
}
String mPhoneNumber = tMgr.getLine1Number();
//Toast.makeText(this, "PHONE NUMEBR "+mPhoneNumber, Toast.LENGTH_SHORT).show();
if(mPhoneNumber.equals(phonenumber))
{
logUser(phonenumber);
Intent intent=new Intent(Login.this,ListActivity.class);
startActivity(intent);
finishAffinity();
}
else
{
etphonenumber.setError("Enter Your Phone Number First");
etphonenumber.requestFocus();
}
}
The phone number inputted should be the number that is currently being used in the android device to login the system.
I am creating a simple applications in which I need READ_CONTACT and CALL_PHONE permissions. I have written below code.
After installation app asks permissions 3 times like this -
1 of 2 read contacts
2 of 2 call and manage phone
1 of 2 read contacts
2 of 2 call and manage phone
1 of 2 read contacts
2 of 2 call and manage phone
Also After granting these permissions app does't open. But when I open app again, it works fine and does not ask permissions again.
I have following code
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case MULTIPLE_REQUESTS: {
if (grantResults.length > 0) {
boolean contactPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean phonePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (contactPermission && phonePermission) {
// write your logic here
} else {
Toast.makeText(this, "Read Contact & Call phone permissions are required", Toast.LENGTH_SHORT).show();
closeNow();
}
}
break;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
+ ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale
(this, Manifest.permission.READ_CONTACTS) ||
ActivityCompat.shouldShowRequestPermissionRationale
(this, Manifest.permission.CALL_PHONE)) {
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.CALL_PHONE},
MULTIPLE_REQUESTS);
}
}
setContentView(R.layout.activity_contact_app_bar);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
}
The permission should be asked when you invoke respective functionality .
I am suspecting the app is getting closed due to closeNow is called .
You need to debug below code .
if (grantResults.length > 0) {
boolean contactPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean phonePermission = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (contactPermission && phonePermission) {
// write your logic here
} else {
Toast.makeText(this, "Read Contact & Call phone permissions are required", Toast.LENGTH_SHORT).show();
closeNow();
}
}
try This Code
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this,
new String[]{ Manifest.permission.READ_CONTACTS, Manifest.permission.CALL_PHONE},
MULTIPLE_REQUESTS);
}
add above code where you want permission
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_REQUESTS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] !=
PackageManager.PERMISSION_GRANTED) {
// Permission has been denied by user
} else {
// Permission has been granted by user
}
return;
}
}
}
}
I have this app that will pick image to gallery and display it to the test using Imageview. My problem is it won't work on Android M. I can pick image but won't show on my test.They say i need to ask permission to access images on android M but don't know how. please help.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.
Type 1- When your app requests permissions, the system presents a dialog box to the user. When the user responds, the system invokes your app's onRequestPermissionsResult() method, passing it the user response. Your app has to override that method to find out whether the permission was granted. The callback is passed the same request code you passed to requestPermissions().
private static final int PICK_FROM_GALLERY = 1;
ChoosePhoto.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v){
try {
if (ActivityCompat.checkSelfPermission(EditProfileActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(EditProfileActivity.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);
startActivityForResult(galleryIntent, PICK_FROM_GALLERY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] 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, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
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;
}
}
Type 2- If you want to give runtime permission back to back in one place then you can follow below link
Android 6.0 multiple permissions
And in Manifest add permission for your requirements
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Note- If Manifest.permission.READ_EXTERNAL_STORAGE produce error then please replace this with android.Manifest.permission.READ_EXTERNAL_STORAGE.
==> If you want to know more about runtime permission then please follow below link
https://developer.android.com/training/permissions/requesting.html
-----------------------------UPDATE 1--------------------------------
Runtime Permission Using EasyPermissions
EasyPermissions is a wrapper library to simplify basic system permissions logic when targeting Android M or higher.
Installation
Add dependency in App level gradle
dependencies {
// For developers using AndroidX in their applications
implementation 'pub.devrel:easypermissions:3.0.0'
// For developers using the Android Support Library
implementation 'pub.devrel:easypermissions:2.0.1'
}
Your Activity (or Fragment) override the onRequestPermissionsResult method:
#Override
public void onRequestPermissionsResult(int requestCode, String[]
permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
Request Permissions
private static final int LOCATION_REQUEST = 222;
Call this method
#AfterPermissionGranted(LOCATION_REQUEST)
private void checkLocationRequest() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if (EasyPermissions.hasPermissions(this, perms)) {
// Already have permission, do the thing
// ...
} else {
// Do not have permissions, request them now
EasyPermissions.requestPermissions(this,"Please grant permission",
LOCATION_REQUEST, perms);
}
}
Optionally, for a finer control, you can have your Activity / Fragment implement the PermissionCallbacks interface.
implements EasyPermissions.PermissionCallbacks
#Override
public void onPermissionsGranted(int requestCode, List<String> list) {
// Some permissions have been granted
// ...
}
#Override
public void onPermissionsDenied(int requestCode, List<String> list) {
// Some permissions have been denied
// ...
}
Link -> https://github.com/googlesamples/easypermissions
-----------------------------UPDATE 2 For KOTLIN--------------------------------
Runtime Permission Using florent37
Installation Add dependency in App level gradle
dependency
implementation 'com.github.florent37:runtime-permission-kotlin:1.1.2'
In Code
askPermission(
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
) {
// camera or gallery or TODO
}.onDeclined { e ->
if (e.hasDenied()) {
AlertDialog.Builder(this)
.setMessage(getString(R.string.grant_permission))
.setPositiveButton(getString(R.string.yes)) { dialog, which ->
e.askAgain()
} //ask again
.setNegativeButton(getString(R.string.no)) { dialog, which ->
dialog.dismiss()
}
.show()
}
if (e.hasForeverDenied()) {
e.goToSettings()
}
}
Link-> https://github.com/florent37/RuntimePermission
public void pickFile() {
int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
CAMERA);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
getActivity(),
new String[]{CAMERA},
PERMISSION_CODE
);
return;
}
openCamera();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
if (requestCode == PERMISSION_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openCamera();
}
}
}
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_CODE);
}
<uses-permission android:name="android.permission.CAMERA" />