Tuesday, 25 June 2019

Android GPS Location LocationListener for run in background Service

Here sharing code for make running background Service to Listen updated Location on particular time interval with using Time

Here Code for background Service

LocationUpdate.java

package com.ksample;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.*;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class LocationUpdate extends Service implements LocationListener {

     Context mContext;

     int USRMTM = 2000;

    // GPS status
    boolean isGPSEnabled = false;

    // Network status
    boolean isNetworkEnabled = false;

    // GPS status
    boolean canGetLocation = false;

    // Notify from background started
    public static String str_receiver = "messageSent";

    private Handler mHandler = new Handler();

    long notify_interval = 1000;

    Intent mintent;

    Location location; // location
    // The minimum distance to change Updates in meters

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 10 meters
    // Update to improve performance

    private static final long MIN_TIME_BW_UPDATES = 180000 * 1; // 1 minute
    // Declaring a Location Manager

    protected LocationManager locationManager;

    public static Boolean SingleEntry = true;

    String currentLongitude,currentLatitude,currentAddress;

    public LocationUpdate(Context context) {
        this.mContext = context;
        mintent = new Intent();
        // commented        mintent.setAction(str_receiver);

        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerTask() {
            @Override            public void run() {
                // Do your stuff                
                 ((MainActivity) mContext).runOnUiThread(new Runnable() {
                    @Override                    
                     public void run() {
                        try {
                            getLocation();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

        }, 0, USRMTM);
    }


    private static final int TWO_MINUTES = 3000 * 60 * 1;

    public Location getLocation() {
        //Update to Accurate Location        
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);
        criteria.setAltitudeRequired(false);
        criteria.setSpeedRequired(false);
        criteria.setCostAllowed(true);
        criteria.setBearingRequired(false);

        //API level 9 and up        criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH);
        criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH);

        //29-08-2018 Upate End
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
           // getting GPS status
            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            // getting network status
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                // First get location from Network Provider
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, criteria, this, null);
                    //criteria                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        try {
                            location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            this.canGetLocation = true;
                            fn_update(location);
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, criteria, this, null);
                    }

                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                            this.canGetLocation = true;
                            fn_update(location);
                        }
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }


    @Override    
     public void onLocationChanged(Location mlocation) {
        try {
            if (mlocation != null) {
                latitude = mlocation.getLatitude();
                longitude = mlocation.getLongitude();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override    
    public void onProviderDisabled(String provider) {
    }

    @Override    
     public void onProviderEnabled(String provider) {
    }

    @Override    
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override    
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override    
    public void onCreate() {
        super.onCreate();
    }

    private class TimerTaskToGetLocation extends TimerTask {
        @Override        public void run() {
            mHandler.post(new Runnable() {
                @Override                public void run() {
                    fn_getlocation();
                }
            });
        }
    }

    boolean mGPSEnable = false;
    boolean isNetworkEnable = false;
    double latitude, longitude;

    private void fn_getlocation() {
        locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
        mGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!mGPSEnable && !isNetworkEnable) {
        } else {
            if (isNetworkEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        Log.e("latitude", location.getLatitude() + "");
                        Log.e("longitude", location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        fn_update(location);
                    }
                }
            }

            if (mGPSEnable) {
                location = null;
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        Log.e("latitude", location.getLatitude() + "");
                        Log.e("longitude", location.getLongitude() + "");
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        fn_update(location);
                    }
                }
            }
        }
    }

    private void fn_update(Location location) {

        currentLongitude = String.valueOf(location.getLongitude());
        currentLatitude = String.valueOf(location.getLatitude());
        getAddressFromLocation(location.getLatitude(), location.getLongitude(), mContext);
    }

    public static class MyReceiver extends BroadcastReceiver {
        public MyReceiver() {
        }

        @Override        public void onReceive(Context context, Intent intent) {

            final double latitude = Double.valueOf(intent.getStringExtra("latutide"));
            final double longitude = Double.valueOf(intent.getStringExtra("longitude"));
            final String Liveaddress = intent.getStringExtra("address");
            currentAddress = Liveaddress;
            Location startPoint = new Location("locationA");
            startPoint.setLatitude(latitude);
            startPoint.setLongitude(longitude);
            double mlatitude = 0;
            try {
                if (!TextUtils.isEmpty(currentLatitude)) {
                    mlatitude = Double.parseDouble(currentLatitude);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            double mlongitude = 0;

            try {

                if (!TextUtils.isEmpty(currentLongitude)) {
                    mlongitude = Double.parseDouble(currentLongitude);
                }

            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            //=======================Match 2 Location Start =-================
            double mlatitude2 = 0;
            try {

                if (!TextUtils.isEmpty(currentLatitude)) {
                    mlatitude = Double.parseDouble(currentLatitude);
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            double mlongitude2 = 0;
            try {

                if (!TextUtils.isEmpty(currentLongitude)) {
                    mlongitude = Double.parseDouble(currentLongitude);
                }


            } catch (NumberFormatException e) {
                e.printStackTrace();
            }

            //======================================Match Seconnd Location End==================
            Location endPoint = new Location("locationB");
            endPoint.setLatitude(mlatitude);
            endPoint.setLongitude(mlongitude);

            //===========================Location C==========
            Location endPointC = new Location("locationC");
            endPointC.setLatitude(mlatitude2);
            endPointC.setLongitude(mlongitude2);


            //==================================End            // Location 1 get Distnace
            double distance = startPoint.distanceTo(endPoint);
            // Location 2 get Distnace
            double distance2 = startPoint.distanceTo(endPointC);

            boolean isAllowLogin;

            if (distance <= 2 || distance2<=2) {
                isAllowLogin = true;
                //=============                String isChecked ="false" ;
                try {
                    if(!Boolean.parseBoolean(isChecked)){
                        Toast.makeText(mContext,"Checked Enable True Location from Settting  ", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                isAllowLogin = false;
            }
        }
    }

    @Override    
     public void onTaskRemoved(Intent rootIntent) {

        Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
        restartServiceIntent.setPackage(getPackageName());
        PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        alarmService.set(
                AlarmManager.ELAPSED_REALTIME,
                SystemClock.elapsedRealtime() + 1000,
                restartServicePendingIntent);
        super.onTaskRemoved(rootIntent);
    }

    ///Address Encoding
    private static final String TAG = "LocationAddress";

    public void getAddressFromLocation(final double latitude, final double longitude, final Context context) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                Geocoder geocoder = new Geocoder(context, Locale.getDefault());
                String result = null;
                try {
                    List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
                    if (addressList != null && addressList.size() > 0) {
                        Address address = addressList.get(0);
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                            sb.append(address.getAddressLine(i)).append("\n");
                        }
                        sb.append(address.getLocality()).append("\n");
                        sb.append(address.getPostalCode()).append("\n");
                        sb.append(address.getCountryName());

                        //===============Updated Address
                        StringBuilder msb = new StringBuilder();

                        String maddress = addressList.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()                        String mcity = addressList.get(0).getLocality();
                        String mstate = addressList.get(0).getAdminArea();
                        String mcountry = addressList.get(0).getCountryName();
                        String mpostalCode = addressList.get(0).getPostalCode();
                        String mknownName = addressList.get(0).getFeatureName();

                        msb.append(maddress).append("\n");
                        result = msb.toString();

                        Log.e(TAG, "" + result.toString());
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Unable connect to Geocoder", e);
                } finally {
                    if (result != null) {

                        currentAddress = result;

                        try {
                            intent.putExtra("latutide", location.getLatitude() + "");
                            intent.putExtra("longitude", location.getLongitude() + "");
                            intent.putExtra("address", result + "");
                            mContext.sendBroadcast(intent);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {

                        try {

                            intent.putExtra("latutide", location.getLatitude() + "");
                            intent.putExtra("longitude", location.getLongitude() + "");
                            intent.putExtra("address", "Unable to get address for this lat-long");
                            mContext.sendBroadcast(intent);

                            // Here we can Api call
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            }
        };
        thread.start();
    }

}

Friday, 21 June 2019

How to display AdView in Bottom with RecyclerView in Xml

Here we design a Layout to display Adview  with RecyclerView 



Select  layouts right click on it Select New and Create Layout resource file. give file name like as you wish here i m giving home.xml and here i share xml  Layout  file code to set Adview at bottom with Recyclerview. here you can take any control as you wish.

home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="@+id/adbhome"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="@string/ads_banner">
</com.google.android.gms.ads.AdView>
<android.support.v7.widget.RecyclerView
android:id="@+id/mrecycle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/adbhome"
android:layout_alignParentTop="true" />
</RelativeLayout>

Android Q updated feature



Here i m sharing some updated features points in simple way about Android Q release.

  •  Android Q having theme Dark mode
  •  Android Q adds a features Desktop mode to view 
  •  Now User can share wifi password using Scan QR code 
  •  Photo effects changes can see in Camera access permission 
  •  Media Play progress display in Notification bar with play on background 
  • Set your swipe notification direction as per your convenient,  like left to dismiss and right to show menu. 
  • Bubbles notification for Application
  • updated Settings panels controls ui 
  • convenient volume setting option with different types of controls Media, Call ,Ring ,Alarm 
  • Notification updated custom user can manage it time to take action and to read it as per convenient then automatically its remove for it. 
  • Navigation Gesture updates 
  • Switch application gestures like Ios between application left or right swipe


Thursday, 20 June 2019

Kotlin Basic Example Sum of Two Digit Number

Kotlin Example Code

Here we are going to share sample code for Using Kotlin making sum of  two numbers.

You can Download Sample Code  Download Here


Code Here like below.

MainActivity.kt

package com.ksample

import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import org.w3c.dom.Text

class MainActivity : AppCompatActivity() {

    //Widget   lateinit var btnSum: Button;
   lateinit var txtSum: TextView;
   lateinit var edtNo1: EditText;
   lateinit var edtNo2: EditText;

    //Context   lateinit var  mcontext: Context

    //Variables    var number1 = 0;
    var number2 = 0;
    var sum = 0;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        mcontext =  this;

        btnSum = findViewById(R.id.btntest);

        edtNo1 = findViewById(R.id.edtNo1);

        edtNo2 =  findViewById(R.id.edtNo2);

        txtSum = findViewById(R.id.txtSum);


        btnSum.setOnClickListener(object : View.OnClickListener{
            override fun onClick(v: View?) {

                //Your code here                
                number1 = Integer.parseInt(edtNo1.getText().toString());
                number2 = Integer.parseInt(edtNo2.getText().toString());
                sum= number1+number2;
                txtSum.setText(""+sum)
                Toast.makeText(mcontext,"Clicke Button"+sum,Toast.LENGTH_LONG).show()
            }
        });


    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp"
        tools:context=".MainActivity">


    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="No 1"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                android:textColor="@android:color/holo_orange_dark"/>

        <EditText
                android:id="@+id/edtNo1"
                android:layout_marginLeft="20dp"
                android:layout_width="204dp"
                android:inputType="number"
                android:layout_height="69dp"/>


    </LinearLayout>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="No 2"
                android:textColor="@android:color/holo_orange_dark"/>


        <EditText
                android:id="@+id/edtNo2"
                android:layout_width="200dp"
                android:layout_marginLeft="20dp"
                android:inputType="number"
                android:layout_height="wrap_content"/>


    </LinearLayout>


    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="5dp">


        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Sum :"
                android:textColor="@android:color/holo_orange_dark"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" 
                app:layout_constraintVertical_bias="0.134"/>


        <TextView
                android:id="@+id/txtSum"
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:text="0.0"
                android:layout_marginLeft="20dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintHorizontal_bias="0.16"
                app:layout_constraintVertical_bias="0.134"/>

    </LinearLayout>


    <Button
            android:text="Sum"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:background="@android:color/holo_orange_dark"
            android:textColor="@android:color/white"
            android:id="@+id/btntest"/>

</LinearLayout>


build.gradle(Module:app)

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.ksample"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

build.gradle(Project:Ksample)

buildscript {
    ext.kotlin_version = '1.3.21'
    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Wednesday, 19 June 2019

Android Studio from Basic Development Introduction with Presentation


Android 9 Pie Updates


Updated Android 9 (API level 28) introduce great new features and capabilities for users and developers.

Some important features points are given below.
  • Device Indoor positioning with Wi-Fi RTT
- support for the IEEE 802.11mc Wi-Fi protocol
- The device must have location services enabled and Wi-Fi scanning turned on
- Need ACCESS_FINE_LOCATION permission
  • Device Display cutout support
- lets you find out the location and shape of the non-functional areas where content shouldn't be displayed.
- use the getDisplayCutout() method.
- attribute, layoutInDisplayCutoutMode, allows your app to lay out its content around a device's cutouts.
- attribute

LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
  • Device Notifications Updated
 Enhanced messaging experience

- The Person class is used to identify people  their avatars and URIs
- other APIs, such as addMessage()
- The Person class also supports the Builder design pattern.

  • Device Channel settings, broadcasts, and Do Not Disturb
You can use the isBlocked() method 
up settings using the new getNotificationChannelGroup() method.
NotificationManager reference

  • Device now Multi-camera support and camera updates
ImageDecoder for drawables and bitmaps

  • Device Animation

HDR VP9 Video, HEIF image compression, and Media APIs
supported in the MediaMuxer and MediaExtractor classes


  • Device Data cost sensitivity in JobScheduler
  • Device Neural Networks API 1.1
  • Device having Autofill framework
  • Device Security enhancements
  • Device having Android Protected Confirmation
  • Device having Hardware security module
  • Device APK signature scheme with key rotation
  • Device Option to allow key decryption only on unlocked devices
  • Device have Legacy encryption support
  • Device Deprecation of WPS
  • Android backups
  • Device Client-side encryption backups
  • Define device conditions required for backup
  • Accessibility
  • Navigation semantics
  • Accessibility pane titles
  • Heading-based navigation
  • Group navigation and output
  • Window change details
  • Rotation
  • Text
  • Power management
  • Privacy changes
  • Limited access to sensors in background
  • Restricted access to call logs





Tuesday, 18 June 2019

How to get Device(Mobile) IME Number in Android Pro-grammatically

Need to add require permission in Android Manifest.xml file


<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Now need to Allow user permission at run time in your AppCompatActivity

public void FindIME() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED) {
            // your READ_PHONE_STATE permission yet not granted.
            DevicePermission();
        } else {
            // your READ_PHONE_STATE permission is already been granted.
            ActivityCompat.requestPermissions(FlashScreen.this, new String[]{Manifest.permission.READ_PHONE_STATE}, PERMISSION_READ_STATE);
            GetIME();
        }
    }

Here we need to ask for user  permission

private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
private void DevicePermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {
   
       new AlertDialog.Builder(FlashScreen.this)
                    .setTitle("Permission Request")
                    .setMessage(getString(R.string.permission_read_phone_state_rationale))
                    .setCancelable(false)
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            //re-request
                            ActivityCompat.requestPermissions(FlashScreen.this,
                                    new String[]{Manifest.permission.READ_PHONE_STATE},
                                    MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
                        }
                    })
                    .setIcon(R.drawable.ic_login)
                    .show();
        } else {
            // READ_PHONE_STATE permission has not been granted yet. Request it directly.
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
                    MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
        }
 }

public void GetIME() {
        String deviceUniqueIdentifier = null;
        TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        if (null != tm) {
            deviceUniqueIdentifier = tm.getDeviceId();
        }
        if (null == deviceUniqueIdentifier || 0 == deviceUniqueIdentifier.length()) {
            deviceUniqueIdentifier = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        }

        IME_Device = deviceUniqueIdentifier;
        Log.i("Device Ime", "Value--------->" + IME_Device);
     
    }

@Override
 public void onRequestPermissionsResult(int requestCode,
 String permissions[], int[] grantResults) {
        switch (requestCode) {

            case MY_PERMISSIONS_REQUEST_READ_PHONE_STATE: {

                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission granted!
                 
                    GetIME();
                } else {
                    // permission denied
                    Toast.makeText(mContext, "Need to allow Read Phone state ..", Toast.LENGTH_LONG).show();
                }
            }
            break;

            case PERMISSION_READ_STATE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission granted!
                 
                } else {
                    // permission denied
                    Toast.makeText(mContext, "Need to allow Read Phone state ..", Toast.LENGTH_LONG).show();
                }

            }
            break;
        }

    }

Find Hours Diffrence in Kotlin

  In Kotlin, determining the difference in hours between two timestamps is a common task, especially in scenarios involving time-based calcu...