An example of GPS positioning in Android _android

Source: Internet
Author: User
Tags date now time interval

GPS positioning is now a lot of mobile phones have the function, and very practical. This paper describes the use of GPs positioning in Android in the form of an example. Share for everyone to use for reference. The specific methods are as follows:

Generally in Android to obtain the current position via GPS, first of all to obtain a Locationmanager instance, through the example of the Getlastknownlocation () method to obtain the first location, the method is described as follows:

void Android.location.LocationManager.requestLocationUpdates (String provider, long mintime, float mindistance, Locationlistener listener)

PROVIDER is the positioning mode, can use GPS positioning (locationmanager.gps_provider) or network positioning (locationmanager.network_provider), this paper is GPS positioning, So use Locationmanager.gps_provider. Mintime is the time interval for location updates. Listener is a position-changing listener that defines a locationlistener (), rewrites onlocationchanged (), and adds the action when the position changes.

The layout files are as follows:

<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:o" rientation= "vertical" 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=". Mainactivity "> <textview android:id=" @+id/txt_time "style=" @style/my_text "android:layout_width=" fi Ll_parent "android:layout_height=" wrap_content "android:text=" Time: "/> <textview android:id=" @+id/txt _lat "style=" @style/my_text "android:layout_width=" fill_parent "android:layout_height=" Wrap_content "Andro" id:text= "Longitude:"/> <textview android:id= "@+id/txt_lng" style= "@style/my_text" android:layout_width= "fi Ll_parent "Android:layout_height= "Wrap_content" android:text= "Latitude:"/> </LinearLayout>

 

The

Mainactivity.java file is as follows:

Package Com.hzhi.my_gps;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Java.util.Timer;
Import Java.util.TimerTask;
Import Android.location.Criteria;
Import android.location.Location;
Import Android.location.LocationListener;
Import Android.location.LocationManager;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Message;
Import android.app.Activity;
Import Android.content.Context;
Import Android.view.Menu;
Import Android.widget.TextView;
  public class Mainactivity extends activity {TextView txt_time;
  TextView Txt_lat;
  TextView txt_lng;
  Locationmanager Lom;
  Location Loc;
  Double lat;
  Double LNG;
  SimpleDateFormat formatter = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
  Date now;
  String str_date;
 
  Timer timer;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
     
    Setcontentview (R.layout.activity_main);
    Get_con ();
     
    Get_gps (); Timer = NEW Timer (True);
  Timer.schedule (Task, 0, 1000); @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action B
    Ar if it is present.
    Getmenuinflater (). Inflate (R.menu.main, menu);
  return true;
    public void Get_gps () {lom = (Locationmanager) getsystemservice (Context.location_service);
     
    loc = Lom.getlastknownlocation (Locationmanager.gps_provider);
      if (loc!= null) {lat = Loc.getlatitude ();
      LNG = Loc.getlongitude ();
      Txt_lat.settext ("Latitude:" + string.valueof (LAT));
    Txt_lng.settext ("Longitude:" + string.valueof (LNG));
      } else{Txt_lat.settext ("Latitude: Unknown");
    Txt_lng.settext ("Longitude: Unknown");
    The Criteria criteria = new criteria ();
    Criteria.setaccuracy (Criteria.accuracy_fine);
    Criteria.setaltituderequired (FALSE);
    Criteria.setbearingrequired (FALSE);
    Criteria.setcostallowed (TRUE);
    Criteria.setpowerrequirement (Criteria.power_low); StringProvider = Lom.getbestprovider (criteria, true);
  Lom.requestlocationupdates (provider, 1000, Los); Locationlistener los = new Locationlistener () {public void onlocationchanged (Location Location) {if (loc
        ation!= null) {lat = Location.getlatitude ();
        LNG = Location.getlongitude ();
        Txt_lat.settext ("Latitude:" + string.valueof (LAT));
      Txt_lng.settext ("Longitude:" + string.valueof (LNG));
        } else{Txt_lat.settext ("Latitude: Unknown");
      Txt_lng.settext ("Longitude: Unknown");
     
    }
    };
     
    public void onproviderdisabled (String provider) {};
     
    public void onproviderenabled (String provider) {};
  public void onstatuschanged (String provider, int status, Bundle extras) {};
   
  };
    Gets the control public void Get_con () {txt_time = (TextView) Findviewbyid (r.id.txt_time);
    Txt_lat = (TextView) Findviewbyid (R.id.txt_lat);
  TXT_LNG = (TextView) Findviewbyid (R.ID.TXT_LNG); } Handler HandleR = new Handler () {public void Handlemessage (msg) {switch (msg.what) {case 1:get_ti
        Me ();
      Break
   
  }
    }
  };   
       TimerTask task = new TimerTask () {public void run () {Message # = new Message ();   
       Message.what = 1;  
    Handler.sendmessage (message);
   
  } 
  };
    Gets the time public void Get_time () {now = new Date (System.currenttimemillis ());
    Str_date = Formatter.format (now);
  Txt_time.settext ("Time:" + str_date);

 }
}

To add permissions to the Androidmanifest.xml file:

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

Before running the GPS satellite, the results of the operation as shown in the following figure:

The reader can try out a place where the outdoor signal is plentiful, and can obtain the GPS position.

I hope this article will help you with your Android program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.