How to send the location information with an Android application including address

Hello again. In this article I will explain how to implement an Android application that uses location objects and retrieves the information for location such as altitude, latitude or longitude, gets an address information belong to those numbers and sends it with an sms to emergency peoples that were chosen before.

First of all, we need to know about the objects and interfaces that we need to use. We need to use “LocationListener” interface to implement methods for location class. Of course we will extend to “Activity” class to implement activities such as onclick, onselect, etc.

We call a LocationManager object. It is the object where we can call the providers. Providers are the services that can be chosen as network, gps or passive providers. Three of them can be arranged to be used according to what is needed and how they are needed. If no internet is accesible, gps would be the best choice, and if network is available, network will work with better results. Passive provider uses the latest information from the cache.

Screenshot from 2016-06-19 21:33:44

Methods are used according to those declarations. Also we need to declare permissions and design the interface of the application. The code for that can be found below.

package com.example.root.multiple_contacts;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MainActivity extends Activity implements LocationListener{

    Context context = null;                         //context provider
    String message;                                 //first message that will be sent
    String message2;                                //second message that will be sent (sending more than 160 characters with sms provider is not possible
    int PICK_CONTACT;
    ContactsAdapter objAdapter;                     //contacts to be displayed
    ListView lv = null;
    EditText edtSearch = null;
    LinearLayout llContainer = null;
    Button btnOK = null;

    Button btnDelete = null;
    RelativeLayout rlPBContainer = null;
    ArrayList<String> selected = new ArrayList<String>();       //selected contact names
    ArrayList<String> numbers = new ArrayList<>();         //selected contact numbers
    Location location;                                     //location object
    List<String> adress = new ArrayList<>();               //address information from geocoder


    @Override
    protected void onCreate(Bundle savedInstanceState) throws SecurityException {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LocationManager locationmanager;
        locationmanager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);

        locationmanager.requestLocationUpdates(locationmanager.GPS_PROVIDER,2000,10,this);
        boolean isNetworkEnabled = locationmanager.isProviderEnabled(locationmanager.NETWORK_PROVIDER);
        boolean isGPSEnabled = locationmanager.isProviderEnabled(locationmanager.GPS_PROVIDER);

        System.out.println("Activation of network provider is: "+isNetworkEnabled);
        System.out.println("Activation of the gps provider is "+isGPSEnabled);
        Criteria cri=new Criteria();
        String provider=locationmanager.getBestProvider(cri,true);

        this.onLocationChanged(location);
        location=locationmanager.getLastKnownLocation(provider);

        System.out.println(locationmanager.getLastKnownLocation(provider));
        context = this;

        rlPBContainer = (RelativeLayout) findViewById(R.id.pbcontainer);
        edtSearch = (EditText) findViewById(R.id.input_search);
        llContainer = (LinearLayout) findViewById(R.id.data_container);
        btnOK = (Button) findViewById(R.id.ok_button);
        //preventing sliding
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        String cityName = "Not Found";
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        try {

            List<Address> addresses = gcd.getFromLocation(location.getLatitude(),location.getLongitude(), 10);
            for (Address adrs : addresses) {
                if (adrs != null) {

                    String city = adrs.getAddressLine(0);

                        cityName = city;
                        adress.add(cityName);
                    System.out.println(adress);

                        System.out.println("city ::  " + cityName);


                    }
                    // // you should also try with addresses.get(0).toSring();



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


        final Button sendmessage=
       (Button) findViewById(R.id.btnSendSMS);
        sendmessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (selected.isEmpty())
                        Toast.makeText(getApplicationContext(), "No contact was chosen for messaging!", Toast.LENGTH_LONG).show();
                    else{

                    message = "Help! I am in an emergency!My latitude is: " +
                            location.getLatitude() + "And my longitude is: " + location.getLongitude() + ". Please" +
                            "check the map for my location. ";
                                  sendmessage(message);
                        message2 = "My precious address is:" +adress.toString();
                        sendmessage(message2);
                    /*ArrayList<String> messages = new ArrayList<String>();

                    for(int i=0;i<selected.size();i++){
                        message = "Help, "+selected.get(i)+"! I am in an emergency!My latitude is: " +
                                location.getLatitude() + "And my longitude is: " + location.getLongitude() + ". Please" +
                                "check the map for my location.";
                        messages.add(message);
                        sendmessage(messages.get(i));
                    }*/
                    Toast.makeText(getApplicationContext(), "Help message has sent!", Toast.LENGTH_LONG).show();}


                }

                catch(Exception e){
                    Toast.makeText(getApplicationContext(),"Send failed. Try not to die.", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
            }
        });


        btnOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                getSelectedContacts();
            }
        });

        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                if(!selected.isEmpty()){
                for(int i=0;i<selected.size();i++){
                    selected.remove(selected.get(i));

                    for(int j=0;i<numbers.size();i++){
                        numbers.remove(numbers.get(j));
                    }
                }
                    Toast.makeText(context, "Some item(s) are deleted",
                            Toast.LENGTH_SHORT).show();}

                else
                    Toast.makeText(context, "No items to delete!",
                            Toast.LENGTH_SHORT).show();

            }
        });

        edtSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3) {
                // When user changed the Text
                String text = edtSearch.getText().toString()
                        .toLowerCase(Locale.getDefault());
                objAdapter.filter(text);

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {

                for (ContactObject bean : ContactsListClass.phoneList) {

                    if (bean.isSelected()) {
                        selected.add(bean.getName());
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub
            }
        });

        addContactsInList();

    }

    private void getSelectedContacts() {

        StringBuffer sb = new StringBuffer();

        for (ContactObject bean : ContactsListClass.phoneList) {

            if (bean.isSelected()&&!selected.contains(bean.getName())&&!numbers.contains(bean.getNumber())){
                selected.add(bean.getName());
                numbers.add(bean.getNumber());

            }
        }


        for (int i = 0; i < selected.size(); i++) {
            sb.append(selected.get(i));
            sb.append(",");
        }


        String s = sb.toString().trim();

        if (TextUtils.isEmpty(s)) {
            Toast.makeText(context, "Select at least one Contact",
                    Toast.LENGTH_SHORT).show();
        } else {

            s = s.substring(0, s.length() - 1);
            Toast.makeText(context, "Selected Contacts : " + s,
                    Toast.LENGTH_SHORT).show();

        }


    }

    private void addContactsInList() {

        Thread thread = new Thread() {
            @Override
            public void run() {

                showPB();

                try {

                    Cursor phones = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null, null, null, null);

                    try {
                        ContactsListClass.phoneList.clear();
                    } catch (Exception e) {

                    }

                    while (phones.moveToNext()) {
                        String phoneName = phones
                                .getString(phones
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String phoneNumber = phones
                                .getString(phones
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        String phoneImage = phones
                                .getString(phones
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));


                        ContactObject cp = new ContactObject();


                        cp.setName(phoneName);
                        cp.setNumber(phoneNumber);
                        cp.setImage(phoneImage);

                        ContactsListClass.phoneList.add(cp);

                    }
                    phones.close();

                    lv = new ListView(context);

                    lv.setLayoutParams(new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.MATCH_PARENT,
                            RelativeLayout.LayoutParams.MATCH_PARENT));

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            llContainer.addView(lv);
                        }
                    });

                    Collections.sort(ContactsListClass.phoneList,
                            new Comparator<ContactObject>() {
                                @Override
                                public int compare(ContactObject lhs,
                                                   ContactObject rhs) {
                                    return lhs.getName().compareTo(
                                            rhs.getName());
                                }
                            });

                    objAdapter = new ContactsAdapter(MainActivity.this,
                            ContactsListClass.phoneList);
                    lv.setAdapter(objAdapter);
                    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        @Override
                        public void onItemClick(AdapterView<?> parent,
                                                View view, int position, long id) {

                            CheckBox chk = (CheckBox) view
                                    .findViewById(R.id.contactcheck);
                            ContactObject bean = ContactsListClass.phoneList
                                    .get(position);
                            if (bean.isSelected()) {
                                bean.setSelected(false);
                                chk.setChecked(false);
                            } else {
                                bean.setSelected(true);
                                chk.setChecked(true);
                            }

                        }
                    });

                } catch (Exception e) {

                    e.printStackTrace();

                }

                hidePB();

            }
        };
        thread.start();

    }

    void showPB() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                rlPBContainer.setVisibility(View.VISIBLE);
                edtSearch.setVisibility(View.GONE);
                btnOK.setVisibility(View.GONE);
            }
        });
    }

    void hidePB() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                rlPBContainer.setVisibility(View.GONE);
                edtSearch.setVisibility(View.VISIBLE);
                btnOK.setVisibility(View.VISIBLE);
            }
        });
    }


    public void sendmessage (String mesaj)
    {
        SmsManager menager1;
        menager1 = SmsManager.getDefault();
        for(int i=0;i<numbers.size();i++){
        menager1.sendTextMessage(numbers.get(i),null,selected.get(i)+" ,"+mesaj,null,null);
        System.out.println(numbers.get(i));
        System.out.println(selected.get(i));}

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        return true;
    }
    @Override
    public void onLocationChanged(Location location) {


    }
    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {
    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

        Toast.makeText(context,"Your location provider is disabled, opening settings",Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
    }

}

Manifest file can be found below;

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


    <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
    <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/emergency"
        android:label="@string/app_name"
        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>

    </application>


</manifest>

 

Main interface(activity_main.xml) can be found like following;

<?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="match_parent"
    android:background="#ad9494"
    >

<EditText
    android:id="@+id/input_search"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Search your contacts"
    android:textSize="25dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="false"
    android:background="#b54e4e"
    android:padding="15dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp" />

<LinearLayout
    android:id="@+id/data_container"
    android:layout_width="match_parent"
    android:layout_height="260dp"
    android:gravity="center|top"
    android:orientation="vertical"
    android:weightSum="1"
    android:layout_below="@+id/input_search"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="false">

</LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DELETE CONTACTS"
        android:id="@+id/btnDelete"
        android:background="#caabab"
        android:layout_alignTop="@+id/ok_button"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"

        android:paddingLeft="15dp"
        android:paddingRight="15dp" />


    <RelativeLayout
    android:id="@+id/pbcontainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#55000000"
    android:clickable="true"
    android:visibility="gone" >

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
</RelativeLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="PANIC!"
        android:id="@+id/btnSendSMS"
        android:background="#af0c0c"
        android:textSize="30dp"
        android:paddingLeft="30dp"
        android:paddingRight="30dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"

        android:textStyle="bold"
        android:layout_marginBottom="10dp" />
    <Button
        android:id="@+id/ok_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ADD CONTACTS"
        android:textSize="15dp"
        android:background="#caabab"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="20dp"
        android:layout_alignBottom="@+id/btnSendSMS"
        android:layout_marginBottom="90dp" />

</RelativeLayout>



 

Also, one must add the icon for the application that will be displayed while launching and to be shown on the screen and also one must choose the contact pictures and add it to /res/drawable. My picture name was yellow.png so it can be changeable. And also the app icon is in /res/mipmap.

Overall, this application will help you to send your information from locationmanager and get the address from geocoder and send it to a receiver that has been choosen before sending.
That is all, if you have any further questions, please ask or tell me any kind of reviews.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s