Monday, 6 March 2017

Cara Menampilkan Dengan Sederhana Koordinat Dari GPS Provider -Android

Gambar 1. Latitude dan Longitude


Salah satu fitur android yang laris  digunakan saat ini yaitu fitur GPS. Fitur GPS pada android dapat digunakan untuk menentukan lokasi kita dan man-share pada orang lain sehingga keberadaan kita diketahui contohnya pada aplikasi gojek, uber dan lainya.

Ada tiga cara pada android untuk menentukan lokasi kita yaitu menggunakan fungsi chip gps, tower selular dan menggunakan lokasi akses poin wifi. Masing-masing cara tersebut punya kelebihan dan kekurangan sehingga dalam menggunakan nya perlu strategi. Strategi tersebut disesuaikan dengan kebutuhan kita terhadap gps. Pada situs Google developer resmi telah merilis strategi itu yang bagus untuk dipahami berikut urlnya: https://developer.android.com/guide/topics/location/strategies.html.

Pada kali ini saya akan memberikan source code bagaimana menampilkan koordinat menggunakan fungsi chip gps/GPS Provider yang tertanam pada handphone. Saya menggunakan GPS Provider karena saya menginginkan keakuratan titik yang diperoleh. Sementara kelemahan menggunakan GPS Provider diantaranya boros batrai, hanya dapat berfungsi diarea terbuka/mudah terganggu oleh bangunan dan untuk mendapatkan suatu titik tertentu memerlukan waktu yang lebih lama dari network provider. Sumber kelemahan dan kelebihan GPS provider:  https://developerlife.com/2010/10/20/gps/


GPSTracker.java

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

public class GPSTracker extends Service implements LocationListener{

    private Context context;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;

    Location location;
    double latitude,longitude;

    LocationManager locationManager;
    AlertDialogManager am = new AlertDialogManager();
    public GPSTracker(Context context){
        this.context = context;
        getLocation();
    }
    private Location getLocation() {
        // TODO Auto-generated method stub
        try{
            locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);

            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);


       

                if (isGPSEnabled){
                    if (location == null){
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 3, this);
                        if (locationManager != null){
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null){
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                } else {
                    showAlertDialog();
                }
            
        }catch(Exception e){
            e.printStackTrace();
        }
        return location;
    }
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(GPSTracker.this);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // Setting Icon to Dialog
        //alertDialog.setIcon(R.drawable.delete);

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
                dialog.cancel();
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    public void showAlertDialog(){
        am.showAlertDialog(GPSTracker.this, "GPS Setting", "Gps is not enabled. Do you want to enabled it ?", false);
    }
    public double getLatitude(){
        if (location != null){
            latitude = location.getLatitude();
        }

        return latitude;
    }

    public double getLongitude(){
        if (location != null){
            longitude = location.getLongitude();
        }

        return longitude;
    }

    public boolean canGetLocation(){
        return this.canGetLocation;
    }
    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        if (location != null){
            this.location = location;
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}

AlertDialogManager.java

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;


public class AlertDialogManager {
    /**
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     *      - pass null if you don't want icon
     * */
    public void showAlertDialog(Context context, String title, String message,
                                Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        if(status != null)
            // Setting alert dialog icon

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

MainActivity.java

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 java.util.ArrayList;

import oddsaydev.getkoordinat.Helper.Datadata;
import oddsaydev.getkoordinat.Helper.MySQLiteHelper;

public class MainActivity extends AppCompatActivity {
    TextView       textView;        TextView     textView3;EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=(TextView)      findViewById(R.id.textView);
      

        Button       button=(Button)      findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GPSTracker gps = new GPSTracker (MainActivity.this);
                double latitude = gps.getLatitude();
                double longitude= gps.getLongitude();
                textView.setText("Latitude: "+latitude+" Longitude: "+longitude);

            }
        });
       
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="oddsaydev.getkoordinat.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ambil Koordinat"
        android:id="@+id/button"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

Jangan lupa menambahkan permission Access Fine Location pada manifest untuk mengakses fitur GPS Provider


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


Hasil source code ini seperti gambar :

Gambar 2. Hasil source code


Aktifkan GPS mu dan dapatkan titik dimana kamu berada

Selamat bereksperimen..

Sekian dan Terima kasih





Artikel Terkait Android

12 comments: