Security exception while fetching android device IMEI number - android

I need to access the IMEI number of android device. I'm not going to publish this android app on playstore. It's for personal use in the organization. Is there any workaround to fetch the IMEI number? Right now I'm geting security exception while fetching IMEI. I have made device admin app. Though I'm not able to access IMEI number.
class MainActivity : AppCompatActivity() {
val REQUEST_CODE = 101
var imei: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// in the below line, we are initializing our variables.
// in the below line, we are initializing our variables.
val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
val imeiTextView = findViewById<TextView>(R.id.idTVIMEI)
// in the below line, we are checking for permissions
// in the below line, we are checking for permissions
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.READ_PHONE_STATE
) != PackageManager.PERMISSION_GRANTED
) {
// if permissions are not provided we are requesting for permissions.
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.READ_PHONE_STATE),
REQUEST_CODE
)
}
// in the below line, we are setting our imei to our text view.
// in the below line, we are setting our imei to our text view.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
imei = telephonyManager.imei
}
imeiTextView.setText(imei)
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String?>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE) {
// in the below line, we are checking if permission is granted.
if (grantResults.size != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// if permissions are granted we are displaying below toast message.
Toast.makeText(this, "Permission granted.", Toast.LENGTH_SHORT).show()
} else {
// in the below line, we are displaying toast message
// if permissions are not granted.
Toast.makeText(this, "Permission denied.", Toast.LENGTH_SHORT).show()
}
}
}
}

Related

HealthConnect Permission Handling: What is the difference between the two else{...} segments?

Im trying to implement permission handling for healthconnect. This is done in the funciton checkPermissionAndRun (strongly inspired by the documentation), however I'm not sure what the difference between the two else{...} code segments is.Both check if the permission is given already, but why do we need 2 of those? Furthermore, is it alright if I call the checkpermissionandrun function once in the oncreate, or should i do this also when interacting with HealthConnect?
class MainActivity : AppCompatActivity() {
// build a set of permissions for required data types
val PERMISSIONS =
setOf(
HealthPermission.createReadPermission(HeartRateRecord::class),
HealthPermission.createWritePermission(HeartRateRecord::class),
HealthPermission.createReadPermission(StepsRecord::class),
HealthPermission.createWritePermission(StepsRecord::class)
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val hcManager = HealthConnectManager(this)
checkPermissionsAndRun(hcManager.healthConnectClient, PERMISSIONS)
}
private fun checkPermissionsAndRun(client: HealthConnectClient, PERMISSIONS: Set<HealthPermission>) {
val requestPermissionActivityContract = PermissionController.createRequestPermissionResultContract()
val requestPermissions =
registerForActivityResult(requestPermissionActivityContract) { granted ->
if (granted.containsAll(PERMISSIONS)) {
//Permission granted text 1
Toast.makeText(applicationContext, "permissions granted 1", Toast.LENGTH_SHORT).show()
} else {
// Lack of required permissions, But what is different to the coroutine else below?
}
}
lifecycleScope.launch {
val granted = client.permissionController.getGrantedPermissions(PERMISSIONS)
if (granted.containsAll(PERMISSIONS)) {
//Permission Granted text 2
Toast.makeText(applicationContext, "permissions granted 2", Toast.LENGTH_SHORT).show()
} else {
//lack of required permissions
requestPermissions.launch(PERMISSIONS)
}
}
}
}
Thank you in advance

Unable to get longitude and latitude kotlin android

Here's my code:
private var longitude = ""
private var latitude = ""
In the oncreateView, I have to do a api call with my latitude and longitude data. But the value of latitude and longitude never change!
//location
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(requireActivity())
// getCurrentLocation
checkPermissions()
//CALL API
val request = Request.Builder()
.url(" API_PATH?latitude=$latitude&longitude=$longitude")
.build()
val client = OkHttpClient()
...
private fun checkPermissions(){
if(ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_DENIED){
ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 1)
}
else{
getLocations()
}
}
private fun getLocations() {
if (ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
requireContext(),
Manifest.permission.ACCESS_COARSE_LOCATION
) != 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
}
fusedLocationProviderClient.lastLocation.addOnCompleteListener {
if(it == null){
Toast.makeText(requireContext(), "sorry can't get the location", Toast.LENGTH_SHORT).show()
}else it.apply {
latitude = it.result.latitude.toString()
longitude = it.result.longitude.toString()
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode== 1){
if(grantResults.isNotEmpty() && grantResults[0]==PackageManager.PERMISSION_GRANTED){
//permission granted
if(ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED){
Toast.makeText(requireContext(), "Permission granted", Toast.LENGTH_SHORT).show()
getLocations()
}
}else{
Toast.makeText(requireContext(), "Permission denied", Toast.LENGTH_SHORT).show()
//denied permission
}
}
}
First, I enter always in th first condition in checkPermissions(). I don't know why. Secondly, I also try to write getLocations() in the first condition in the first if in checkPermissions(). But longitude and latitude are never update.
Can you help me please, I am on this case for a long time and I have no idea.
I think you always enter the first condition in checkPermissions() because you haven't yet granted the permissions.
I think you need to request the permissions where the TODO code is commented out.
It will be something like:
// You can directly ask for the permission.
requestPermissions(CONTEXT,
arrayOf(Manifest.permission.REQUESTED_PERMISSION),
REQUEST_CODE)
Found from https://developer.android.com/training/permissions/requesting
I hope that steers you in the right direction.
If you want to cheat for testing, you can go to Settings -> Apps -> Your app -> Permissions and enable the permissions and then re-test. Of course, you'll have to do the request in code for the users of your app before you release the app.

`onRequestPermissionsResult()` is not working in Fragment-Kotlin

Problem:
I have done this LocationPermission task with activity but I want to do it with the fragment. In Fragment method onRequestPermissionsResult() is not being called.
There are many answers to this question but unfortunately non of them worked for me. Some of those answers are in java which is not applicable in kotlin, for instance, one answer says using 'FragmentCompat' this problem can be solved but we don't have FragmentCompat in Kotlin.
What I did so far?
I followed this question and many others.
Before ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
After:
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
though requestPermissions is depricated But nothing worked so far.
PLEASE DO CONSIDER KOTLIN LANGUAGE FOR ANSWERS
Code in Fragment:
fun RequestLocationPermission()
{
Log.d(TAG, "RequestLocationPermission: ")
if(ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
if(ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), Manifest.permission.ACCESS_FINE_LOCATION)){
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
}
else{
ActivityCompat.requestPermissions(requireActivity(), arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 1)
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),1)
}
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
Toast.makeText(requireContext(), "Request Permission Called", Toast.LENGTH_SHORT).show()
Log.d(TAG, "onRequestPermissionResult Called ")
when (requestCode) {
1 -> when {
grantResults.isEmpty() ->
// If user interaction was interrupted, the permission request
// is cancelled and you receive empty arrays.
Log.d(TAG, "User interaction was cancelled.")
grantResults[0] == PackageManager.PERMISSION_GRANTED ->{
// Permission was granted.
locationPermission = true
fetchLocation()
}
else -> {
// Permission denied.
Toast.makeText(requireContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}

Ask permissions just showing granted

I followed the simple steps to ask for multiple permissions at once, here is my code for the permission request:
class MainActivity : AppCompatActivity() {
private val permissionCode = 100
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getPermissions()
}
fun getPermissions() {
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.NFC, Manifest.permission.INTERNET),
permissionCode
)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
permissionCode -> {
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted
Toast.makeText(this, "Permissions granted", Toast.LENGTH_SHORT).show()
} else {
// Permission denied
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show()
}
}
}
}
When I am starting the app I dont get any dialog to accept or deny the permissions and just get the toast "Permissions granted" but if I check the permissions in the app info I dont see any permissions granted. What I am doing wrong? Can someone help me?
Neither INTERNET nor NFC are permissions that need to be requested at runtime. Just having them in the manifest (via <uses-permission> elements) is sufficient.
Only permissions with a protection level of dangerous need to be requested at runtime — this table lists those. INTERNET and NFC are normal permissions, not dangerous.

"Unexpected tokens" error in function call

I'm having some trouble with Kotlin syntax, it requires a semicolon inside a function call (?!).
I was simply attempting to convert the code from AltBeacon website, the one used to get coarse location permissions. Here's what I've come up with on a rush:
class MainActivity : AppCompatActivity() {
val TAG = "MAIN_ACTIVITY"
val PERMISSION_REQUEST_COARSE_LOCATION = 1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
val builder = AlertDialog.Builder(this)
builder.setTitle("This app needs location access")
builder.setMessage("Please grant location access so this app can detect beacons.")
builder.setPositiveButton(android.R.string.ok, null)
builder.setOnDismissListener {
val permissions = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION)
requestPermissions(permissions, PERMISSION_REQUEST_COARSE_LOCATION)
}
builder.show()
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
PERMISSION_REQUEST_COARSE_LOCATION-> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "coarse location permission granted")
} else {
val builder = AlertDialog.Builder(this)
builder.setTitle("Functionality limited")
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null)
builder.setOnDismissListener { }
builder.show()
}
}
}
}
}
Compiler has issues with this line:
requestPermissions(permissions, PERMISSION_REQUEST_COARSE_LOCATION)
Unexpected tokens (use ';' to separate expressions on the same line)
Everything is ok with kotlin syntax here.
The problem is that you have a strange invisible symbol at the end of that line. I pasted that code in notepad++ and saw this:
So just delete it and compilation will succeed.

Categories

Resources