Baidu SDK positioning, not application, used in their own projects,

Source: Internet
Author: User

Package Com.example.baidulocdemo_2;import Com.baidu.location.bdlocationlistener;import Com.baidu.location.locationclient;import Com.baidu.location.locationclientoption;import Com.baidu.location.locationclientoption.locationmode;import android.content.context;/** * * @author Baidu * */public Class Locationservice {private Locationclient client = Null;private locationclientoption moption,diyoption;private Object Objlock = new Object ();/*** * * @param locationcontext */public locationservice (Context locationcontext) {Synchron Ized (Objlock) {if (client = = NULL) {client = new locationclient (locationcontext); Client.setlocoption ( Getdefaultlocationclientoption ());}}} locationservice/*** * * @param listener * @return */public boolean registerlistener (Bdlocationlistener listener) {bool Ean issuccess = false;if (listener! = null) {Client.registerlocationlistener (listener); issuccess = true;} return issuccess;} public void Unregisterlistener (Bdlocationlistener listener) {if (listener! = null) {client.unRegisterlocationlistener (Listener);}} /*** * * @param option * @return issuccesssetoption */public boolean setlocationoption (locationclientoption option) {Boole An issuccess = false;if (option = null) {if (client.isstarted ()) client.stop ();D iyoption = Option;client.setlocoption ( option);} return issuccess;} Public Locationclientoption getOption () {return diyoption;} /*** * * @return defaultlocationclientoption */public locationclientoption getdefaultlocationclientoption () {if ( Moption = = null) {moption = new locationclientoption (); Moption.setlocationmode (locationmode.hight_accuracy);//optional, The default high precision, set positioning mode, high precision, low power consumption, only device Moption.setcoortype ("Bd09ll");//optional, default GCJ02, set the returned positioning result coordinate system, if the use of Baidu map, the proposed set to BD09LL; Moption.setscanspan (3000);//optional, default 0, that is, to locate only once, set the interval for initiating a location request is greater than or equal to 1000ms is valid moption.setisneedaddress (TRUE);//optional, Set whether address information is required, default does not require Moption.setisneedlocationdescribe (true);//optional, set whether address description is required Moption.setneeddevicedirect (false);//optional , set whether the device orientation result Moption.setlocationnotify (false) is required,//optional, default false, set whether to output GP according to 1S1 frequency when GPS is actives result Moption.setignorekillprocess (true);//optional, default True, the location SDK inside is a service, and put in a standalone process, set whether to kill the process at stop, default does not kill MOPTION.S    Etisneedlocationdescribe (TRUE);//optional, default false, set whether to require positional semantics results, can be obtained in bdlocation.getlocationdescribe, the result is similar to "near the gate of Beijing Tian ' an"    Moption.setisneedlocationpoilist (TRUE);//optional, default false, set whether POI results are required, can be obtained in bdlocation.getpoilist Moption.setignorecacheexception (false);//optional, default false, set whether to collect crash information, default collection}return moption;} public void Start () {synchronized (Objlock) {if (client! = null &&!client.isstarted ()) {Client.start ();}}} public void Stop () {synchronized (Objlock) {if (client! = null && client.isstarted ()) {client.stop ();}}} Stop

Package Com.example.baidulocdemo_2;import Android.app.activity;import Android.os.bundle;import android.view.Menu; Import Android.view.menuitem;import Android.widget.textview;//public class Mainactivity extends Activity {//private TextView areatextview;////@Override//protected void OnCreate (Bundle savedinstancestate) {//super.oncreate ( Savedinstancestate);//setcontentview (r.layout.activity_main);//}//}import Com.baidu.location.bdlocation;import Com.baidu.location.bdlocationlistener;import Com.baidu.location.poi;import Android.app.activity;import Android.os.bundle;import Android.text.method.scrollingmovementmethod;import Android.view.view;import Android.view.view.onclicklistener;import android.widget.button;import android.widget.textview;/*** * Single point positioning example, Used to show basic positioning results, configuration in Locationservice.java default configuration can also be modified in Locationservice * default configuration content from the developer forum for developers Long-term questions * * @author Baidu * */PU Blic class Mainactivity extends Activity {//private locationservice locationservice;private Locationservice LocationservIce;private TextView locationresult;private Button startlocation;//bdlocation location = new Bdlocation (); @ overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( savedinstancestate);//-----------Demo view config------------setcontentview (r.layout.activity_main); Locationresult = (TextView) Findviewbyid (R.id.areatextview); Locationresult.setmovementmethod (Scrollingmovementmethod.getinstance ());//startlocation = (Button) findViewById ( r.id.addfence); locationservice = new Locationservice (Getapplicationcontext ());//mvibrator//= (Vibrator) Getapplicationcontext (). Getsystemservice (Service.vibrator_service);//Writelog.getinstance (). Init (); Initialize the log///Sdkinitializer.initialize (Getapplicationcontext ());//Get the Locationservice instance, it is recommended that only 1 location instances are initialized in the application, and then use, You can refer to other examples of activity, all of which obtain the Locationservice.registerlistener (Mlistener) of the Locationservice instance in this way;//register listener int type = Getintent (). Getintextra ("from", 0); if (type = = 0) {locationservice.setlocationoptIon (Locationservice.getdefaultlocationclientoption ()); else if (type = = 1) {locationservice.setlocationoption (locationservice.getoption ());} Locationservice.start ();}  oncreate/***** * @see copy funtion to your project * to locate the result callback, rewrite the Onreceivelocation method, you can copy the following code directly into your project to modify * */private Bdlocationlistener Mlistener = new Bdlocationlistener () {@Overridepublic void onreceivelocation (bdlocation location) {/ /TODO auto-generated method stubif (null! = location&& Location.getloctype ()! = Bdlocation.typeservererror) {Str Ingbuffer sb = new StringBuffer,//Sb.append ("Time:"),/** * times can also be obtained using the Systemclock.elapsedrealtime () method since the boot, The time of each callback, * Location.gettime () refers to the time the service ends the result, and if the position does not change, then the time is not changed *///Sb.append (Location.gettime ());//Sb.append ("\nerror Code: ");//Sb.append (Location.getloctype ());//Sb.append (" \nlatitude: ");//Sb.append (Location.getlatitude ());// Sb.append ("\nlontitude:");//Sb.append (Location.getlongitude ());//Sb.append ("\nradius:");//Sb.append ( Location.getraDius ());//Sb.append ("\ncountrycode:");//Sb.append (Location.getcountrycode ());//Sb.append ("\ncountry:");// Sb.append (Location.getcountry ());//Sb.append ("\ncitycode:");//Sb.append (Location.getcitycode ());//Sb.append ("\ Ncity: "); Sb.append (Location.getprovince ()); Sb.append (Location.getcity ());//Sb.append (" \ndistrict: "); Sb.append ( Location.getdistrict ());//Sb.append ("\nstreet:") Sb.append (Location.getstreet ());//Sb.append ("\NADDR:");// Sb.append (Location.getaddrstr ());//Sb.append ("\ndescribe:");//Sb.append (Location.getlocationdescribe ());// Sb.append ("\ndirection (not all devices has value):");//Sb.append (Location.getdirection ());//Sb.append ("\npoi:"); if (location.getpoilist () = null&&!location.getpoilist (). IsEmpty ()) {for (int i = 0; i < location.getpoilist ( ). Size (); i++) {Poi poi = (POI) location.getpoilist (). get (i); Sb.append (Poi.getname () + ";");}} if (location.getloctype () = = Bdlocation.typegpslocation) {//GPS location result Sb.append ("\nspeed:"); sb.append(Location.getspeed ());//Unit: Km/hsb.append ("\nsatellite:"); Sb.append (Location.getsatellitenumber ()); Sb.append ("\ Nheight: "); Sb.append (Location.getaltitude ());//unit: M Sb.append (" \ndescribe: "); Sb.append (" GPs positioning succeeded ");} else if (location.getloctype () = = Bdlocation.typenetworklocation) {//Network location result//operator information Sb.append ("\noperationers:"); Sb.append (Location.getoperators ()); Sb.append ("\ndescribe:"); Sb.append ("Network positioning succeeded");} else if (location.getloctype () = = Bdlocation.typeofflinelocation) {//Offline location result Sb.append ("\ndescribe:"); Sb.append (" Offline positioning is successful, offline location results are also valid ");} else if (location.getloctype () = = Bdlocation.typeservererror) {sb.append ("\ndescribe:"); Sb.append ("Server-side network location failed, Can feedback the IMEI number and the approximate positioning time to [email protected], will be traced to the cause ");} else if (location.getloctype () = = bdlocation.typenetworkexception) {sb.append ("\ndescribe:"); Sb.append ("Network different causes location failure, Please check that the network is unobstructed "); else if (location.getloctype () = = bdlocation.typecriteriaexception) {sb.append ("\ndescribe:"); Sb.append (" Unable to obtain a valid location based on the failure of the location, generally because of the phone's cause, in flight mode is generally caused by this result, can beTry to focus on the mobile phone "); Logmsg (Sb.tostring ()); Locationresult.settext (Sb.tostring ());}}};}

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.baidulocdemo_2 "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses- SDK android:minsdkversion= "android:targetsdkversion="/> <uses-permission android:name= "Android" Oid.permission.ACCESS_COARSE_LOCATION "> </uses-permission> <uses-permission android:name=" Android.permission.ACCESS_FINE_LOCATION "> </uses-permission> <uses-permission android:name=" Android.permission.ACCESS_WIFI_STATE "> </uses-permission> <uses-permission android:name=" Android.permission.ACCESS_NETWORK_STATE "> </uses-permission> <uses-permission android:name=" Android.permission.CHANGE_WIFI_STATE "> </uses-permission> <uses-permission android:name=" Android.permission.READ_PHONE_STATE "> </uses-permission> <uses-permission android:nAme= "Android.permission.WRITE_EXTERNAL_STORAGE" > </uses-permission> <uses-permission android:name= " Android.permission.INTERNET "/> <uses-permission android:name=" Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "> </uses-permission> <uses-permission android:name=" Android.permission.READ_LOGS "> </uses-pe rmission> <uses-permission android:name= "Android.permission.VIBRATE"/> <uses-permission android:name= " Android.permission.WAKE_LOCK "/> <uses-permission android:name=" Android.permission.WRITE_SETTINGS "/> < Application android:allowbackup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/ap P_name "Android:theme=" @style/apptheme "> <meta-data android:name=" Com.baidu.lbsapi.API_KEY "Android:value=" Pwgrdbn3f4x605lzdognwst0 "/> <!--Http://lbsyun.baidu.com/apiconsole/key---& Lt;activity android:name=". Mainactivity "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.baidu.l Ocation. Locationservice "android:enabled=" true "android:process=": Remote > <intent-filter&                Gt <action android:name= "com.baidu.location.service_v2.2" > </action> </intent-filte R> </service> </application></manifest>

<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 "    tools:context= "${relativepackage}.${activityclass}" >    <textview        android:id= "@+id/ Areatextview "        android:layout_width=" wrap_content "        android:layout_height=" Wrap_content "        android: text= "@string/hello_world"/></relativelayout>

The above pro-test available

http://lbsyun.baidu.com/sdk/download?selected=location, download the jar file at this URL


Baidu SDK positioning, not application, used in their own projects,

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.