Tutorial Android : Mengakses Posisi Saat Ini dengan GPS

Saat kita membuat sebuah aplikasi layanan berbasis lokasi (location-based service), aplikasi yang kita buat harus dapat mengetahui posisi penggunanya berada saat itu. Cara yang paling umum adalah dengan menggunakan perangkat GPS. Dengan menggunakan GPS, aplikasi dapat mengetahui lokasi pengguna dan dapat memberikan konten yang relevan dengan lokasi tersebut.

The devil is in the details, walaupun mudah dibicarakan, terkadang ada beberapa kendala pada saat implementasi. Semoga tutorial ini bisa memberi sedikit pencerahan, sekaligus sebagai cacatan penulis:mrgreen:, untuk memulai membuat aplikasi berbasis lokasi di telepon genggam berbasis Android.

Sekedar informasi, program yang akan dibuat dikembangkan menggunakan Eclipse Galileo dan Windows 7. Semoga tidak bermasalah saat dijalankan di IDE atau sistem operasi lainnya😀. Selain itu, akan muncul banyak istilah yang lumrah digunakan di bahasa pemrograman Java.

Membuat Project Baru

Langkah pertama yang dilakukan adalah membuat project baru di Eclipse. Deskripsi project dapat dilihat di Gambar 1.

Gambar 1 Membuat project baru.

Menambah permission di AndroidManifest.xml

Untuk dapat mengakses GPS, kita perlu menambahkan permission di AndroidManifest.xml. Jika permission tidak dicantumkan, aplikasi yang akan dibuat tidak bisa berjalan. Berikut adalah kode AndroidManifest.xml yang telah dimodifikasi.

File : AndroidManifest.xml

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

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".GPSSample"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

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

Menambahkan LocationListener

Agar aplikasi yang kita buat dapat berhubungan dengan GPS, kita memerlukan LocationManager dan LocationListener. LocationManager menyediakan akses ke layanan lokasi di Android. Salah satu layanan yang tersedia adalah update lokasi geografis dari perangkat yang digunakan. LocationManager akan mengabarkan setiap perubahan lokasi geografis kepada LocationListener. LocationListener inilah yang nantinya akan kita ubah sesuai dengan kebutuhan kita.

Hal di atas dapat diimplementasikan dalam dua langkah. Pertama, kita buat sebuah class yang mengimplementasikan LocationListener (LocationListener adalah sebuah interface). Ada empat buah method yang harus diimplementasikan, yaitu :

Di fungsi onLocationChanged inilah nilai latitude dan longitude lokasi pengguna akan diterima oleh objek LocationListener. Untuk saat ini, lokasi geografis yang dibaca akan ditampilkan menggunakan Toast. Implementasi dari tahap ini adalah inner class MyLocationListener berikut :

/**
* MyLocationListener
*/
public class MyLocationListener implements LocationListener{
// Dipanggil saat ada perubahan lokasi geografis pengguna
@Override
public void onLocationChanged(Location location) {
// Mendapatkan nilai latitude dari lokasi terbaru
double latitude = location.getLatitude();

// Mendapatkan nilai longitude dari lokasi terbaru
double longitude = location.getLongitude();

// Menampilkan lokasi terbaru menggunakan Toast
String message = "Lokasi saat ini :\n" +
"Latitude  = " + latitude + "\n" +
"Longitude = " + longitude;
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
}

// Dipanggil saat provider dinon-aktifkan oleh pengguna
@Override
public void onProviderDisabled(String provider) {
String message = "GPS disabled";
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
}

// dipanggil saat provider diaktifkan oleh pengguna
@Override
public void onProviderEnabled(String provider) {
String message = "GPS enabled";
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
}

// dipanggil saat ada perubahan status pada provider
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}

Tahap selanjutnya adalah menginisiasikan LocationManager dan LocationListener di aplikasi kita. Pada kasus ini, keduanya diinisiasi di method onCreate dari activity utama aplikasi kita. Dengan demikian, pada saat activity dijalankan, aplikasi kita akan meminta layanan lokasi yang diperlukan.

        // Inisiasi LocationManager dan LocationListener
LocationManager myLocationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, myLocationListener);

Berikut adalah kode lengkap dari activity utama aplikasi yang dibuat :

File : GPSSample.java

<pre>package com.example.gpssample;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class GPSSample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// Inisiasi LocationManager dan LocationListener
LocationManager myLocationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, myLocationListener);
}

/**
* MyLocationListener
*/
public class MyLocationListener implements LocationListener{
// Dipanggil saat ada perubahan lokasi geografis pengguna
@Override
public void onLocationChanged(Location location) {
// Mendapatkan nilai latitude dari lokasi terbaru
double latitude = location.getLatitude();

// Mendapatkan nilai longitude dari lokasi terbaru
double longitude = location.getLongitude();

// Menampilkan lokasi terbaru menggunakan Toast
String message = "Lokasi saat ini :\n" +
"Latitude  = " + latitude + "\n" +
"Longitude = " + longitude;
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
}

// Dipanggil saat provider dinon-aktifkan oleh pengguna
@Override
public void onProviderDisabled(String provider) {
String message = "GPS disabled";
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
}

// dipanggil saat provider diaktifkan oleh pengguna
@Override
public void onProviderEnabled(String provider) {
String message = "GPS enabled";
Toast.makeText(getApplicationContext(),
message, Toast.LENGTH_LONG).show();
}

// dipanggil saat ada perubahan status pada provider
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}

Menjalankan Program

Tahap selanjutnya adalah menjalankan program yang kita buat. Jika anda akan menjalankan program langsung di smartphone, pastikan GPS diaktifkan dan telah terkunci. Selamat bersabar menanti:mrgreen:. Setelah terkunci, aplikasi akan terus menerus menampilkan perubahan lokasi pengguna.

Jika anda akan menjalankan program di emulator, masalah yang harus dihadapi adalah tidak tersedianya GPS di komputer yang kita gunakan. Alhasil kalau applikasi kita jalankan, tidak ada lokasi geografis yang ditampilkan.

Gambar 2 Program yang dijalankan.

Solusinya : beli smartphone Android:mrgreen:. Kalau budget anda terbatas, ada fitur Eclipse yang dapat kita gunakan untuk mengirimkan data GPS ke emulator. Pertama-tama, kita masuk ke DDMS. (Pilih WindowOpen PerspectiveDDMS). Kemedian kita debug aplikasi yang kita buat. Kemudian, pilih tab Emulation Control. Di bagian ini terdapat bagian Location Controls.

Gambar 3 Location controls di DDMS Eclipse.

Di bagian Location Controls inilah kita dapat memasukkan data longitude dan latitude secara manual. Masukkan nilai longitude dan latitude yang akan dikirimkan ke emulator, kemudian tekan tombol send. Sekarang, aplikasi GPSSample yang telah kita buat akan menampilkan posisi geografis pengguna yang telah dikirimkan.

Gambar 4 Lokasi saat ini ditampilkan oleh program.

Sekian. Pertanyaan dan masukan sangat ditunggu🙂.

Project lengkapnya dapat diunduh di Google Code.

68 thoughts on “Tutorial Android : Mengakses Posisi Saat Ini dengan GPS

  1. Those with a smaller budget have to be savvy shoppers to get
    the Prada purse they desire for this summer. Black is thought of as “the sexy color,” but other colors can be very sexy, too.
    The unique yellow colorway louis vuitton luggage is a
    perfect way to bring the sunshine with you everywhere you go.

  2. While continuing with acting roles here and there, Sarandon’s real passion lately seems to be running a business.
    In the big city of Detroit, there are also lots of choices when it comes to Michigan hotels.
    You can make some different resolutions and can arrangement for game nights, dance party,
    theme party, outdoor fun, decorate party place etc that truly help to carry
    a perfect family time.

  3. On site SEO to make money online always starts with keyword research.
    Learning to make cash online with internet online affiliate marketing also can keep you from making costly mistakes whenever you lastly do
    have your individual product. Moreover, as long as you have a
    personal computer or laptop that is supported with the Internet facility
    you can carry out your respective tasks with
    utmost ease and convenience.

  4. Dehydration and exposure to heat can lead to a number of severe
    health risks in people and pets. This is bad news for workers in the building trades, many of whom considered themselves recession proof, secure in the
    belief that there would always be a market for their work, because people would always
    need basic housing-related work done, such as roof repair or replacement plumbing.

    The best place to look will have to be on the internet.

  5. They too are some attractive things to see, and tourists are able to tour them from the
    inside, in the morning and in the afternoon. It is and maybe obtain the data
    where you’ll get lowest motel premiums as well as
    travel ideas while likely to all of these a couple of cities.
    The museum building was once a prison where some of the meanest criminals were kept.

  6. You’re so interesting! I don’t think I have read something like this before.

    So great to discover another person with some original
    thoughts on this issue. Really.. many thanks for starting this up.
    This web site is something that’s needed on the web, someone with a bit of originality!

  7. Thank you a bunch for sharing this with all of us you really understand
    what you’re speaking approximately! Bookmarked.
    Please additionally consult with my site =).

    We can have a hyperlink change agreement between us

  8. What you posted was actually very logical.
    However, what about this? suppose you added a little content?
    I mean, I don’t want to tell you how to run your website,
    however suppose you added a headline that makes people
    want more? I mean Tutorial Android : Mengakses Posisi Saat Ini dengan GPS | The
    Beacon of Amon Dîn is kinda plain. You ought to peek at Yahoo’s home page and see how they write post headlines to grab people to open the links.

    You might add a related video or a picture or two to get people
    excited about what you’ve got to say. In my opinion, it would
    make your posts a little bit more interesting.

  9. I was suggested this website by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my trouble.
    You’re amazing! Thanks!

  10. Hi there! I could have sworn I’ve been to this website before
    but after browsing through some of the post I realized it’s new to me.
    Nonetheless, I’m definitely glad I found it and I’ll be book-marking and checking back often!

  11. I’m really enjoying the design and layout of your site.
    It’s a very easy on the eyes which makes it much more
    pleasant for me to come here and visit more often. Did you hire out a designer to create your theme?
    Excellent work!

  12. Have you ever considered about adding a little bit
    more than just your articles? I mean, what you say is important and everything.
    Nevertheless just imagine if you added some great images or videos to give
    your posts more, “pop”! Your content is excellent but with images and clips, this site could undeniably be one of the
    most beneficial in its field. Very good blog!

  13. Hey there just wanted to give you a quick heads up and let you know a few of the
    pictures aren’t loading correctly. I’m not sure why but I think its a linking issue.

    I’ve tried it in two different web browsers and both show the same outcome.

  14. Greetings! I know this is kinda off topic but I was wondering if you knew where I could
    get a captcha plugin for my comment form? I’m using the same blog platform as
    yours and I’m having difficulty finding one? Thanks a lot!

  15. With havin so much written content do you ever run into any issues of plagorism or copyright infringement?

    My website has a lot of unique content I’ve either created myself or outsourced but it appears a lot of it is popping
    it up all over the internet without my agreement.
    Do you know any methods to help stop content from being stolen? I’d genuinely appreciate it.

  16. Attractive section of content. I just stumbled upon your site and in accession capital to claim that I acquire actually enjoyed account
    your blog posts. Any way I will be subscribing to your feeds or even I fulfillment you get admission to constantly quickly.

  17. Pretty section of content. I just stumbled upon your web site and in accession capital to say that I get in fact loved account
    your weblog posts. Any way I will be subscribing on your feeds or even I achievement you access consistently quickly.

  18. Hey just wanted to give you a quick heads up and
    let you know a few of the pictures aren’t loading correctly.
    I’m not sure why but I think its a linking issue. I’ve
    tried it in two different web browsers and both show the same results.

  19. I’m amazed, I must say. Rarely do I come across a blog that’s equally educative and
    amusing, and let me tell you, you’ve hit the nail on the head.

    The issue is an issue that too few folks are speaking intelligently about.
    I’m very happy I stumbled across this in my hunt for something regarding this.

  20. My spouse and I stumbled over here coming from a different web page and thought I might as
    well check things out. I like what I see so now i am following
    you. Look forward to looking into your web page for a second time.

  21. This design is spectacular! You most certainly know how to keep
    a reader entertained. Between your wit and your videos, I was
    almost moved to start my own blog (well, almost…HaHa!) Excellent job.
    I really enjoyed what you had to say, and more than that, how you presented it.
    Too cool!

  22. This is very fascinating, You’re a very professional blogger.
    I’ve joined your feed and look forward to in the hunt for more of your fantastic post.

    Additionally, I have shared your website in my social networks

  23. Interesting blog! Is your theme custom made or did you download it from somewhere?
    A design like yours with a few simple tweeks would really make my blog stand out.
    Please let me know where you got your theme.
    Appreciate it

  24. Hey, I think your website might be having browser compatibility issues.
    When I look at your blog in Ie, it looks fine but when opening in Internet
    Explorer, it has some overlapping. I just wanted to give you a quick heads up!
    Other then that, great blog!

  25. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time
    a comment is added I get three emails with the same comment.
    Is there any way you can remove me from that service? Thanks a lot!

  26. Good post. I learn something new and challenging on sites I stumbleupon everyday.
    It will always be exciting to read through content from other authors and use a little something from other sites.

  27. hello there and thank you for your information – I have definitely picked up anything new from right
    here. I did however expertise some technical points using this site, since I
    experienced to reload the website many times previous to I could get it to load properly.

    I had been wondering if your web host is OK?
    Not that I am complaining, but sluggish loading instances times will sometimes affect your placement in google and could damage
    your high-quality score if ads and marketing with
    Adwords. Well I am adding this RSS to my e-mail and
    could look out for a lot more of your respective exciting content.
    Make sure you update this again very soon.

  28. Have you ever thought about adding a little bit more than just your articles?

    I mean, what you say is fundamental and all. But think of if you added
    some great pictures or video clips to give your posts more, “pop”!
    Your content is excellent but with pics and clips, this website could undeniably
    be one of the greatest in its field. Very good blog!

  29. Hey! This is my first visit to your blog! We are a
    collection of volunteers and starting a new initiative in a community in the same niche.
    Your blog provided us useful information to work on. You have done a outstanding job!

  30. Do you mind if I quote a couple of your posts as long as I provide credit and
    sources back to your blog? My website is in the exact same niche as yours
    and my users would really benefit from a lot of the information you
    present here. Please let me know if this ok with you. Cheers!

  31. You actually make it appear really easy along with your presentation however I find this topic to be
    actually something that I think I would never understand.
    It kind of feels too complex and extremely vast for me.
    I am looking ahead on your next submit, I will try to get the grasp of it!

  32. Unquestionably consider that that you said. Your favorite
    justification appeared to be on the net the easiest factor to understand of.

    I say to you, I certainly get annoyed even as other
    people think about concerns that they just do not know about.
    You controlled to hit the nail upon the top as neatly as outlined out
    the whole thing with no need side effect , other people can take a signal.
    Will probably be back to get more. Thanks

  33. Write more, thats all I have to say. Literally, it seems as though you relied on the video
    to make your point. You definitely know what youre talking about,
    why throw away your intelligence on just posting videos to your weblog when you could be giving us something
    informative to read?

  34. We’re a gaggle of volunteers and starting a brand new scheme in our community.

    Your website provided us with valuable information to work on. You have done an impressive
    job and our entire neighborhood might be thankful
    to you.

  35. Please let me know if you’re looking for a writer for your blog.
    You have some really great articles and I believe I would be a good asset.
    If you ever want to take some of the load off, I’d love to write some material for your blog in exchange for
    a link back to mine. Please send me an email if interested.
    Many thanks!

  36. While as of now, the general public does not know what exactly caused the break
    up of Pitt and Jolie, the stories in upcoming days
    and weeks will certainly be explosive. This is easily seen by the price that
    some people and companies will pay for a particular domain name.

    Uniquely human, laughter is, first and foremost, a social signal–it disappears when there is no audience, which may be as small as
    one other person–and it binds people together.

  37. To counter this, mentally at least, we need to feed our thoughts with something that can at
    least help us escape from real life and,
    at the same time, help us relinquish our stressful thoughts.
    While it has always been my understanding that Thai families are so close knit because of the incredibly
    strong bonds which exist within the group. This is unlike other relationships where you are limited to the experience and the pleasures of your partner only.

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