I want to programmatically get the phone number in Android Studio.
I've tried this: (and it is causing crashes)
TelephonyManager tMgr =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
What is wrong? Any other ways to get the phone number?
I think you need <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
private String getMyPhoneNO() {
TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
return mPhoneNumber;
}
with
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
} else {
String phoneNumber = getMyPhoneNO();
}
in Activity/Fragment
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
String phoneNumber = getMyPhoneNO();
}
}
}
You need to add
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
to manifest + request the permission on runtime for newer android versions.
https://developer.android.com/training/permissions/requesting.html
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
Otherwise you can see a explaining error in the stacktrace.
Related
I have a weird bug, I have an app that registers a Brodcast whenever I call to a number it pops up a webpage.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerBrodcasts();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.READ_CALL_LOG},
MY_PERMISSIONS_REQUEST);
} else {
Toast.makeText(this, "Brodcast registered.", Toast.LENGTH_SHORT).show();
finish();
}
}
private void registerBrodcasts(){
IntentFilter filter = new IntentFilter();
filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(new CallReceiver(), filter);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST) {
if (grantResults.length > 0) {
boolean phoneLogsPermission = grantResults[1] == PackageManager.PERMISSION_GRANTED;
boolean phoneCallPermision = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (phoneLogsPermission && phoneCallPermision) {
Toast.makeText(this, "Permissions granted, we can call now.", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(this, "Please give permissions to the app", Toast.LENGTH_SHORT).show();
}
}
}
}
So, this is how it works, When I open my app it pops up the two permissions I need to request, Phone Call and Phone Logs meanwhile I'm giving access to this permissions registerBrodcasts(); have launched and registered my brodcast.
But here is the bug, If I request the permissions at runtime and try to call after giving this permissions my brodcast does not launch, but, if I go to the app settings and give them manually, the brodcast works without problems.
I dont know why from my app giving this permissions does not register my brodcast but giving them manually does.
This is the brodcast
public class CallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "Intercepted call " + phoneNumber, Toast.LENGTH_LONG).show();
if (phoneNumber.equals("123456789")) {
Intent browserIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://myweb.com"));
browserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(browserIntent);
}
}
}
I suspect that when I give the permissions to the app, my brodcast has been registered without such permissions, but If I move the registerBrodcasts() method to my onRequestPermissionResults it also does not work
These are all my permissions, which I only need to ask for call_phone and read_call_logs
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.NEW_OUTGOING_CALL" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
I made an Android App, which have some permissions, everything is ok but problem is that when user don't click on Allow or Deny(on Permission Dialog at first time app launch) button with in few seconds(approx 3 to 5 seconds) then my app not functioning properly it's register page, login and some other functions not working, if user click within few seconds then its work properly without any issue, i also check this from Internet but nobody clear my issue please help. FCM token not generating from Firebase.
Error is:-
E/FirebaseInstanceId: Unable to get master token
java.lang.SecurityException: getDeviceId: Neither user 10493 nor current process has android.permission.READ_PHONE_STATE.
at android.os.Parcel.readException(Parcel.java:2004)
at android.os.Parcel.readException(Parcel.java:1950)
at com.android.internal.telephony.ITelephony$Stub$Proxy.getDeviceId(ITelephony.java:5030)
at android.telephony.TelephonyManager.getDeviceId(TelephonyManager.java:1013)
at com.Abc.AppName.FirebaseInstanceIDService.id(FirebaseInstanceIDService.java:63)
at com.Abc.AppName.FirebaseInstanceIDService.onTokenRefresh(FirebaseInstanceIDService.java:35)
at com.google.firebase.iid.FirebaseInstanceIdService.zza(Unknown Source:187)
at com.google.firebase.iid.FirebaseInstanceIdService.handleIntent(Unknown Source:306)
at com.google.firebase.iid.zzc.run(Unknown Source:4)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Manifest:-
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE"/>
Splash:-
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.INTERNET,
android.Manifest.permission.ACCESS_NETWORK_STATE,
android.Manifest.permission.READ_PHONE_STATE,
Manifest.permission.CALL_PHONE
};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST);
} else {
callNextActivity();
}
} else {
callNextActivity();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
callNextActivity();
} else {
Toast.makeText(mContext, R.string.permission_denied, Toast.LENGTH_LONG).show();
}
}
}
}
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
FirebaseInstanceID:-
#Override
public void onTokenRefresh() {
token = FirebaseInstanceId.getInstance().getToken();
device_id = id(this);
sharedPreferences = getSharedPreferences(getString(R.string.prefs), 0);
sharedPreferences.edit().putString("fcm_token", token).apply();
device_id = sharedPreferences.getString(PREF_UNIQUE_ID, "");
Log.e("fcm_token", token + " " + device_id);
executeMethod();
}
public synchronized static String id(Context context) {
if (uniqueID == null) {
SharedPreferences sharedPrefs = context.getSharedPreferences(context.getString(R.string.prefs), Context.MODE_PRIVATE);
uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);
if (uniqueID == null) {
mngr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
}
uniqueID = mngr.getDeviceId();
Log.e("UNIQUEID", uniqueID);
sharedPrefs.edit().putString(PREF_UNIQUE_ID, uniqueID).apply();
}
}
return uniqueID;
}
You can use another activity to request permissions. If user allows, just start your main activity, else kill request activity or show popup to warn user.
The problem is you are trying to get id of the device in onTokenRefresh . This method will be called as soon as the app gets installed and opened first time . By this time your app wont have the permission .
So solution to this problem .
In onTokenRefresh just save the token in shared preferences and when you reach the activity ,request for permission and after permission is granted get the token from shared preferences and device id and do your stuff .
I have problem with permissions. What should I do to stop my app from crashing?
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1 && resultCode == RESULT_OK && data != null){
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I just added this in my OnCreate method
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 225);
And it seems to work, is there any better solution?
If putting in your onCreate() works I would check whether you put it in the manifest in the correct place because that has caused me issues in the past.
Make sure <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> is after the first manifest closing tag and before the first <Application ...
For example:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.mypackagename">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application...
try this :
//check permission is granted or no
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, RESULT_LOAD_IMG);
}
else
{
//your code
}
If your target build version is API 23 or higher, just check that the permission is granted or not.
Go to Settings -> Apps and then tap on your app. In Permissions option enable the Storage permission. But it is not the permanent solution.
Well i do something like u want. I give u simply code how to do this :)
Here i checking permission(i call this method in fragment, make this in activity)
#TargetApi(23)
public void checkStoragePermission() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (settingsDrawerFragment != null) {
settingsDrawerFragment.onPermissionGranted();
}
return;
}
if (this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager
.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
REQUEST_CODE_EXTERNAL_STORAGE);
return;
}
if (settingsDrawerFragment != null) {
settingsDrawerFragment.onPermissionGranted();
}
}
This check permission with auto message
Also i make onRequestPermissions
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
grantResults) {
switch (requestCode) {
case REQUEST_CODE_AUDIO_RECORD:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startBrowseActivity();
} else {
Utils.showToast(this, getString(R.string.audio_permission_denied));
}
break;
case REQUEST_CODE_EXTERNAL_STORAGE:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (settingsDrawerFragment != null) {
settingsDrawerFragment.onPermissionGranted();
}
} else {
if (settingsDrawerFragment != null) {
closeSettingsDrawer();
}
Utils.showToast(this, getString(R.string.storage_permission_denied));
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
break;
}
}
Remember to make methods in activity. On fragment check it.
Finally i make something like this to check permissions in fragment
public void setHomeStreamSource(int position) {
if (position == STORAGE_CLOUD_CACHE) {
preferenceHelper.putInt(getString(R.string.preferences_usb_prefs), getString(R.string
.preferences_video_source), MainActivity.SOURCE_CLOUD);
closeDrawer();
Utils.showToast(activity, getString(R.string.source_selected));
} else if (position == STORAGE_USB) {
((MainActivity) activity).checkStoragePermission();
}
}
Hope this sample code help u well
I am new to android and I am working in an android existing project.The app is crashing on android version >6.0, with below exception.Basically app is selecting photo from gallery which is working fine for the first time and on second time onwards the app is crashing giving permission denial exception.
java.lang.SecurityException: Permission Denial: reading
com.google.android.apps.photos.contentprovider.MediaContentProvider
uri
content://com.google.android.apps.photos.contentprovider/0/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F1022/ORIGINAL/NONE/256350537
from pid=7789, uid=10145 requires the provider be exported, or
grantUriPermission()
I have gone through few links and checked that android has introduce run time permissions and I have used below code to check the runtime permission.
The things I have tried so far...
Added permission in manifest.
2.Checking the runtime permission from code.
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
Log.d("Enter", "onRequestPermissionsResult: ");
switch (requestCode){
case REQUEST_CODE_PERMISSION:{
Map<String,Integer> perms = new HashMap<>();
//Initialize the map with the permissions
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION,PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.CAMERA,PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE,PackageManager.PERMISSION_GRANTED);
// perms.put(Manifest.permission.READ_USER_DICTIONARY,PackageManager.PERMISSION_GRANTED);
//Fill with actual results from user
if (grantResults.length > 0){
for (int i = 0 ; i < permissions.length ; i++){
perms.put(permissions[i],grantResults[i]);
//check for all permissions
if (perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){
Log.d("Permission Granted", "onRequestPermissionsResult: ");
}else{
Log.d("Some", "onRequestPermissionsResult: ");
//if (perms.get(Manifest.permission.ACCESS_COARSE_LOCATION))
if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CAMERA)
|| ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.ACCESS_COARSE_LOCATION)
|| ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.READ_EXTERNAL_STORAGE)){
new DialogInterface.OnClickListener(){
#Override
public void onClick (DialogInterface dialog, int which){
switch (which){
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermission();
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
}else{
Toast.makeText(this,"Go to Settings and enable Permissions",Toast.LENGTH_LONG).show();
}
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener){
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK",okListener)
.setNegativeButton("Cancel",okListener)
.create()
.show();
}
}
And the line where it is crashing is :-
if (checkAndRequestPermission()){
InputStream fis = getContentResolver().openInputStream(Uri.parse(url)); //Crashing Line
BitmapFactory.decodeStream(fis, null, o);
fis.close();
}
Below are the permissions used in My Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_USER_DICTIONARY"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="com.google.android.apps.photos.permission.GOOGLE_PHOTOS"/>
<!-- <uses-permission android:name="com.google.android.apps.photos.permission.GOOGLE_PHOTOS"/>-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<!-- The following two permissions are not required to use
Google Maps Android API v2, but are recommended. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="com.google.android.apps.photos.permission.GOOGLE_PHOTOS"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-feature android:name="android.hardware.location" android:required="true" />
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
The problem is not with your manifest permissions, but rather the URI being used. How did you get the URI? The logcat output tells you that the URI is for a content provider which was not exported or that the URI was not provided in an Intent which granted temporary access to the ContentProvider.
After a lot of research I was able to fix the issue.The error was causing since the google photos needs a persistable URI of images,even if you have all codes for runtime permission and flags in Manifest file.
With the help of below answer I have fixed my issue.
https://stackoverflow.com/a/29588566/1842304
Note down all your permission that are working in manifest below android M. We dont need any additional permission for android M. We have to just request at runtime.
And request your permission like this. Change your permission(only dangerous permissions) as they are in manifest. Put this in onCreate
/// granting permission ////
if(!checkPermission())
{
requestPermission();
}
/////////////////////////////
And in class add these
/////////////////////// permission for marshmallow ///////////////////
private boolean checkPermission(){
int result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
int result2 = ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_PHONE_STATE);
int result3 = ContextCompat.checkSelfPermission(this, Manifest.permission.PROCESS_OUTGOING_CALLS);
int result4 = ContextCompat.checkSelfPermission(this, Manifest.permission.PROCESS_INCOMING_CALLS);
int result5 = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
if (result1 == PackageManager.PERMISSION_GRANTED && result2 == PackageManager.PERMISSION_GRANTED &&
result3 == PackageManager.PERMISSION_GRANTED && result4 == PackageManager.PERMISSION_GRANTED
&& result5 == PackageManager.PERMISSION_GRANTED){
return true;
} else {
//Toast.makeText(this,"You don't have permission to use further features",Toast.LENGTH_LONG).show();
return false;
}
}
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.MODIFY_PHONE_STATE) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.PROCESS_OUTGOING_CALLS) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.PROCESS_INCOMING_CALLS) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CALL_PHONE)){
Toast.makeText(this,"Application needs permission to use your camera, calls, storage and location.",Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_PHONE_STATE,
Manifest.permission.MODIFY_PHONE_STATE, Manifest.permission.PROCESS_OUTGOING_CALLS,
Manifest.permission.PROCESS_INCOMING_CALLS, Manifest.permission.CALL_PHONE},1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
grantResults[1] == PackageManager.PERMISSION_GRANTED &&
grantResults[2] == PackageManager.PERMISSION_GRANTED &&
grantResults[3] == PackageManager.PERMISSION_GRANTED &&
grantResults[4] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"Permission Granted.",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this,"Permission Denied.",Toast.LENGTH_LONG).show();
}
break;
}
}
////////////////////////////////////////////////////////////////////////
Try this Solution
in your OnCreate() method
#Override
protected void onCreate(Bundle savedInstanceState)
{
// your code
.................
// call dynamic permission
check_SD_CARD_Permissions();
}
public void check_SD_CARD_Permissions()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = this.checkSelfPermission("Manifest.permission.WRITE_EXTERNAL_STORAGE");
permissionCheck += this.checkSelfPermission("Manifest.permission.READ_EXTERNAL_STORAGE");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
in AndroidManifest.xml
add these permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
and targetSdkVersion must be 23
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="23" />
Build your project with
Version : Android 6.0
and finally in project.properties target must be 23
target=android-23
it's working for me
If the device is running Android 6.0 or higher when im trying to get phone number using getLine1Number():
java.lang.SecurityException: Requires READ_PHONE_STATE: Neither user 10184 nor current process has android.permission.READ_PHONE_STATE.
This is coming out.
I declared permission as :
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
In Android 6.0, you need to explicitly ask the user to grant the permissions. Just declaring it in the manifest isn't enough.
This article in the docs is a great place to start learning the new model, but I'll give a brief summary.
Every time you perform an action that requires a "dangerous permission," you need to check if the permission is currently granted, because the user can revoke it at any time.
This can be done with the checkSelfPermission method.
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
// We do not have this permission. Let's ask the user
}
You can request the permission with the requestPermissions method, as such
ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_READ_STATE);
Where PERMISSION_READ_STATE is a constant integer defined by you to check in the callback method later.
You will then override onRequestPermissionsResult in your activity and see if the permission was granted. If it was, you can go ahead and preform the dangerous action.
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_READ_STATE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission granted!
// you may now do the action that requires this permission
} else {
// permission denied
}
return;
}
}
}
public class MainActivity extends AppCompatActivity {
TextView textView;
String device_unique_id,IMEI;
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
}
public void GetImei(View view)
{
loadIMEI();
}
public void loadIMEI() {
// Check if the READ_PHONE_STATE permission is already available.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
// get_imei_data();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
} else {
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
IMEI = mngr.getDeviceId();
device_unique_id = Settings.Secure.getString(this.getContentResolver(),
Settings.Secure.ANDROID_ID);
textView.setText(device_unique_id+"----"+mngr.getDeviceId());
// READ_PHONE_STATE permission is already been granted.
Toast.makeText(this,"Alredy granted",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,#NonNull int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Toast.makeText(this,"Alredy DONE",Toast.LENGTH_SHORT).show();
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
IMEI = mngr.getDeviceId();
device_unique_id = Settings.Secure.getString(this.getContentResolver(),Settings.Secure.ANDROID_ID);
textView.setText(device_unique_id+"----"+mngr.getDeviceId());
} else {
Toast.makeText(this,"ehgehfg",Toast.LENGTH_SHORT).show();
}
}
}