Saturday 8 August 2015

Automatic Update Current Location With Full Address based on Service

CurrentLocation.java (Main_Activity.java)


package com.karthic.currentlocationaddress;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

@SuppressWarnings("deprecation")
public class CurrentLocation extends ActionBarActivity {


    public static TextView lat,log,sub,fullad,Dateandtime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_current_location);
         lat=(TextView) findViewById(R.id.longitude);
        log=(TextView) findViewById(R.id.longitv);
        sub=(TextView) findViewById(R.id.subloacltv);
        fullad=(TextView) findViewById(R.id.Fulladtv);
        Dateandtime=(TextView) findViewById(R.id.datetime);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.current_location, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        super.onOptionsItemSelected(item);
        switch(item.getItemId())
        {
            case R.id.Get_Address:

                    startService(new Intent(this, GpsService.class));    
                break;
            case R.id.Exit

                stopService(new Intent(this, GpsService.class));
                this.finish();

            break;
        }
return true;
    }
}


GpsService.java 





package com.karthic.currentlocationaddress;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class GpsService extends Service
{
       public static final String BROADCAST_ACTION = "Hello World";
       private static final int TWO_MINUTES = 1000 * 60 * 2;
       public LocationManager locationManager;
       public MyLocationListener listener;
       public Location previousBestLocation = null;
       public static String local,sub;
       public static String  route_id;
       //public static float Speed;
       public static String  periorty;
       public static long distanceInMeters;
      

        Intent intent;
        int counter = 0;
    @Override
    public void onCreate()
    {
        super.onCreate();
        intent = new Intent(BROADCAST_ACTION);    
       
    }

    @Override
//    public void onStart(Intent intent, int startId)
//    {     
//          Toast.makeText(getApplicationContext(), "Your location sharing Statted", Toast.LENGTH_SHORT).show();
//        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//        listener = new MyLocationListener();       
//        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER , 1000, 0, listener);
//        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , 1000, 0, listener);
//       
//       
//    }
    public  void  onStart(Intent intent,  int startId)
    {
       
        Toast.makeText(getApplicationContext(), "Your location sharing Statted", Toast.LENGTH_SHORT).show();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        listener =new MyLocationListener();       
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER , 1000, 0, listener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , 1000, 0, listener);
//        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
//        wacklock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "no sleep");
//        wacklock.acquire();
    }
   
    public IBinder onBind(Intent intent)
    {
       
       
        return null;
    }

    protected boolean isBetterLocation(Location location, Location currentBestLocation)
    {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta <-TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
        // If the new location is more than two minutes older, it must be worse
        } else if (isSignificantlyOlder)
        {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),currentBestLocation.getProvider());
        // Determine location quality using a combination of timeliness and accuracy
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
          return provider2 == null;
        }
        return provider1.equals(provider2);
    }

    public void onDestroy()
    {      
   
        super.onDestroy();          
        Toast.makeText(getApplicationContext(), "Your location sharing stoped", Toast.LENGTH_SHORT).show();

        locationManager.removeUpdates(listener);       
    }  

    public static Thread performOnBackgroundThread(final Runnable runnable)
    {
        final Thread t = new Thread( ) {
            @Override
            public void run() {
                try
                {
                    runnable.run();                  
                }  finally 
                {

                }
            }
        };
        t.start();
        return t;
    }

public class MyLocationListener implements LocationListener
   
{        @SuppressLint("SimpleDateFormat")
        public void onLocationChanged(final Location loc)
        {
            Log.i("**************************************","Location changed");
            if(isBetterLocation(loc, previousBestLocation)) {
                double lo= loc.getLatitude();
                double log= loc.getLongitude();               
                intent.putExtra("Latitude", loc.getLatitude());
                intent.putExtra("Longitude", loc.getLongitude());    
                intent.putExtra("Provider", loc.getProvider());                
                sendBroadcast(intent);                
                Float Speed=((loc.getSpeed() * 3600)/1000);
                 Geocoder geoCoder = new Geocoder(GpsService.this, Locale.getDefault());
                 StringBuilder builder = new StringBuilder();               
                 try {
                    
                     List<Address> address = geoCoder.getFromLocation(lo, log, 1);
                    
                     int maxLines = address.get(0).getMaxAddressLineIndex();
                    
                     for (int i=0; i<maxLines; i++)
                     {
                     local =address.get(0).getSubLocality();
                     String addressStr = address.get(0).getAddressLine(i);
                     builder.append(addressStr);
                     builder.append(" ");
                    // Toast.makeText(getApplicationContext(), " Your Current local :"+local+" ", Toast.LENGTH_SHORT).show();
                     }
                                     String fnialAddress = builder.toString();              
                 SimpleDateFormat sdff = new SimpleDateFormat("hh:mm:ss aa   dd/MM/yyyy");
                 String currentDateandTime = sdff.format(new Date());
                 String latitude = new Double(lo).toString();
                 String longitude = new Double(lo).toString();                                                                         CurrentLocation.lat.setText(latitude);
                 CurrentLocation.log.setText(longitude);                                                                                    CurrentLocation.sub.setText(local);
                 CurrentLocation.fullad.setText(fnialAddress);
                 CurrentLocation.Dateandtime.setText(currentDateandTime);
                 }
              
              catch (IOException e)
                 {
                 }
                   catch (NullPointerException e)
                   {
                      
                   }
            }
           
        }

        public void onProviderDisabled(String provider)
        {
          
        }
        public void onProviderEnabled(String provider)
        {
          //  Toast.makeText( getApplicationContext(), "Your GPS Enabled", Toast.LENGTH_SHORT).show();
        }
        public void onStatusChanged(String provider, int status, Bundle extras)
        {

        }        

  }
}




                    activity_current_location.xml

 <RelativeLayout 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:background="@color/DarkBlue"
    android:textAlignment="center"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:text="Current Location with Full Address"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@color/white" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/tableLayout1"
        android:layout_centerHorizontal="true"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:gravity="center" >

        <TableRow
            android:id="@+id/latitv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Latitude     "
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/white" />

            <TextView
                android:id="@+id/longitude"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="latitv"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/white" />
        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Longitude  "
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/white" />

            <TextView
                android:id="@+id/longitv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="longitv"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/white" />
        </TableRow>

        <TableRow
            android:id="@+id/tableRow3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView6"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Sub locality     "
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/white" />

            <TextView
                android:id="@+id/subloacltv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="subloacltv"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/white" />
        </TableRow>

        <TableRow
            android:id="@+id/tableRow4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView8"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Full Address     "
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/white" />

            <TextView
                android:id="@+id/Fulladtv"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="Fulladtv"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/white" />

        </TableRow>

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/textView7"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Date and Time   "
                android:textColor="@color/white"
                android:textAppearance="?android:attr/textAppearanceMedium" />

            <TextView
                android:id="@+id/datetime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Date and Time"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/white" />

        </TableRow>

    </TableLayout>

</RelativeLayout>

AndroidMainifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.karthic.currentlocationaddress"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
       <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".CurrentLocation"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
       
         <service
            android:name="com.karthic.currentlocationaddress.GpsService"
            android:enabled="true" >
            <intent-filter>
                <action android:name="com.karthic.currentlocationaddress.GpsService" >
                </action>
            </intent-filter>
        </service>
       
    </application>

</manifest>

ScreenShots for output

                          

   choose menu option then select  get Address
 



Your current location will be update on your layout 

Finally choose your Exit optin from menu





 

Send Whatsapp Message via PHP Code

  How to Send and Receive Messages in WhatsApp using PHP In this tutorial you will see How to Send and Receive Messages in WhatsApp using PH...