Friday 28 June 2019

Android Spinner background customize using xml Selector

Here sharing to customize background design of Spinner item  with costume xml file to put in resource drawable  folder and set it in xml Spinner item.

create this xml file in res/drawable folder with name spinner_background.xml
do code for it like as below


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item >
      <layer-list>
        <item>
          <shape>
            <stroke android:width="1dp" android:color="#dddddd" />
            <padding  android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp"/>
            <solid android:color="#FFFFFF" />
        </shape>
       </item>
        <item ><bitmap android:gravity="right|center" android:src="@mipmap/ic_downarrow" />
        </item>
    </layer-list></item>
</selector>


here you need to set ic_downarrow image in mipmap folder as per you need design. will look in Spinner 
right side this image.


Now in your layout,xml file with Spinner item do set this xml file to display costume spinner background 



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Spinner
        android:id="@+id/spnitem"
        android:layout_width="200dp"
        android:layout_gravity="center_horizontal"
        android:layout_height="@dimen/editext_size"
        android:overlapAnchor="false"
        android:textSize="@dimen/reg_text_size"
        android:background="@drawable/spinner_background"        />

</LinearLayout> 

Thursday 27 June 2019

Android updated Api features for Camera to Text detection Example

Here sharing Android  updated Api Features for Optical character recognition(OCR).  with using Camera pictures able to read character for it and can share that read Character to other apps.
To create Application in Android studio follow below steps

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="yourpackageName">
    <uses-permission android:name="android.permission.CAMERA"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" 
        android:value="ocr"/>        
    </application>
</manifest>

build.gradle

dependencies {
    compile 'com.google.android.gms:play-services-vision:11.0.4'}

activity_main.xml

Here we also use Button to share character to other apps.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="5"
    tools:context="Yourpackage.MainActivity">
    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="4" />

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_margin="8dp"
        android:layout_weight="1"
        android:gravity="center"
        android:textStyle="bold"
        android:background="@drawable/mboarder"
        android:text="@string/txt_message"
        android:textColor="@android:color/black"
        android:textSize="20sp" />
    <Button
        android:id="@+id/btnShare"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share"
        android:textAllCaps="false"
        android:background="@color/colorAccent"
        android:layout_marginBottom="5dp"
        android:textColor="@android:color/white"
        android:layout_gravity="center_horizontal"/>
</LinearLayout>


MainActivity.java


package your.packageNamehere;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.text.TextBlock;
import com.google.android.gms.vision.text.TextRecognizer;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    SurfaceView mCameraView;
    TextView mTextView;
    CameraSource mCameraSource;

    private static final String TAG = "MainActivity";
    private static final int requestPermissionID = 101;
    Button btnShare;
    String ReadString;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mCameraView = findViewById(R.id.surfaceView);
        mTextView = findViewById(R.id.text_view);
        btnShare = findViewById(R.id.btnShare);

        btnShare.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {

                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT,ReadString);
                sendIntent.setType("text/plain");
                startActivity(sendIntent);

            }
        });

        startCameraRead();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != requestPermissionID) {
            Log.d(TAG, "Got permission result" + requestCode);
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            return;
        }

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            try {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                mCameraSource.start(mCameraView.getHolder());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void startCameraRead() {
        final TextRecognizer ReadText = new TextRecognizer.Builder(getApplicationContext()).build();
        if (!ReadText.isOperational()) {
            Log.w(TAG, "Detector yet not allow ");
        } else {
            mCameraSource = new CameraSource.Builder(getApplicationContext(), ReadText)
                    .setFacing(CameraSource.CAMERA_FACING_BACK)
                    .setRequestedPreviewSize(1280, 1024)
                    .setAutoFocusEnabled(true)
                    .setRequestedFps(2.0f)
                    .build();
            mCameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
                @Override                public void surfaceCreated(SurfaceHolder holder) {
                    try {

                        if (ActivityCompat.checkSelfPermission(getApplicationContext(),
                                Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.CAMERA},
                                    requestPermissionID);
                            return;
                        }
                        mCameraSource.start(mCameraView.getHolder());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                }

                @Override
                public void surfaceDestroyed(SurfaceHolder holder) {
                    mCameraSource.stop();
                }
            });

            ReadText.setProcessor(new Detector.Processor<TextBlock>() {
                @Override                
                public void release() {
                }
               @Override
                public void receiveDetections(Detector.Detections<TextBlock> detections) {
                    final SparseArray<TextBlock> items = detections.getDetectedItems();
                    if (items.size() != 0 ){

                        mTextView.post(new Runnable() {
                            @Override                            public void run() {
                                StringBuilder stringBuilder = new StringBuilder();
                                for(int i=0;i<items.size();i++){
                                    TextBlock item = items.valueAt(i);
                                    stringBuilder.append(item.getValue());
                                    stringBuilder.append("\n");
                                }
                                mTextView.setText(stringBuilder.toString());
                                ReadString  =  stringBuilder.toString();
                            }
                        });
                    }
                }
            });
        }
    }
}

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();
    }

}

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...