Get location and weather information with Baidu SDK

Source: Internet
Author: User

The following implementation through the Baidu SDK to obtain geographical location and weather information, please refer to the Baidu development documentation

1. Download the latest library file in the relevant. The compressed files of so files out, the corresponding schema of so files into the developer's own application of the corresponding structure of the folder, it is recommended that all put in, the program compatibility will greatly improve, will locsdk_5. X.jar files are copied to the project's Libs directory, so you can use the Baidu Positioning SDK in the program.

2. Set Androidmanifest.xml

< Span style= "FONT-FAMILY:SIMSUN; FONT-SIZE:14PX "> Declare service components in the Application tab, each with its own separate location service

<  Service Android:  name  =   "COM.BAIDU.LOCATION.F"  android:  enabled=   android:  Process=   " : Remote " >  </ Service >  

"Important Reminders"

After locating the SDKv3.1 version, the following permissions are no longer required, please cancel the claim, otherwise the application installation will fail due to the enhanced rights management of the Android 5 multi-account system.

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

3. Declaring usage rights

<span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:14PX;" ><!--This permission for network positioning--><uses-permission android:name= "Android.permission.ACCESS_COARSE_LOCATION" > </uses-permission><!--This permission to access the GPS location--><uses-permission android:name= "Android.permission.ACCESS_ Fine_location "></uses-permission><!--for accessing WiFi network information, WiFi information will be used for network location--><uses-permission android: Name= "Android.permission.ACCESS_WIFI_STATE" ></uses-permission><!--get carrier information to support interfaces that provide operator information-- <uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE" ></uses-permission><!-- This permission is used to get WiFi access, WiFi information will be used for network location--><uses-permission android:name= "Android.permission.CHANGE_WIFI_STATE" ></uses-permission><!--used to read the current status of the phone--><uses-permission android:name= "android.permission.READ_ Phone_state "></uses-permission><!--write extended storage, write data to the expansion card for writing offline location data--><uses-permission android:name = "Android.permission.WRITE_EXTERNAL_STORAGE" ></uses-permission><!--access network, network location needs to surf the internet--><uses-permission android:name= "Android.permission.INTERNET"/><!-- SD card Read permission, user writes offline location data--><uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >< /uses-permission><!--allows an app to read low-level system log files--><uses-permission android:name= "Android.permission.READ_LOGS "></uses-permission></span>

Set Acesskey

The use of SDK5.0 needs to be set up accesskey in Mainfest.xml, the incorrect settings will cause the location and the geo-fencing service to not work properly, and the correct settings must be accesskey.

Set accesskey, add in the Application tab

 <meta-data android:name="Com.baidu.lbsapi.API_KEY" Android:value="key" />//key: Developer Application key        

For the use of related function classes, please refer to the Baidu Development documentation, attached to your own writing to obtain geographical location and weather Locationservice.java:

Package Com.lenovo.realvideocamera.service;import Org.json.jsonarray;import Org.json.jsonexception;import Org.json.jsonobject;import Android.annotation.suppresslint;import Android.app.service;import Android.content.intent;import Android.content.sharedpreferences;import Android.graphics.bitmap;import Android.os.handler;import Android.os.ibinder;import Android.os.message;import Android.text.TextUtils;import Android.util.log;import Com.baidu.location.bdlocation;import Com.baidu.location.bdlocationlistener;import Com.baidu.location.locationclient;import Com.baidu.location.locationclientoption;import Com.baidu.location.locationclientoption.locationmode;import Com.lenovo.realvideocamera.r;import Com.lenovo.realvideocamera.util.dateutil;import Com.lenovo.realvideocamera.util.fileutil;import Com.lenovo.realvideocamera.util.httputil;import com.lenovo.realvideocamera.util.imageutil;/** * location, Weather Service * @ Author Jackie * */public class Locationservice extends Service implements BdlocationlisteneR {Private String TAG = "Locationservice";p ublic locationclient locationclient;//Baidu map location Clientprivate bdlocation bdlocation;//Baidu Map location information private Bitmap weatherbitmap;//weather thumbnails bitmap@overridepublic ibinder onbind (Intent Intent) {log.i ( TAG, "Onbind"); return null;} @Overridepublic void OnCreate () {super.oncreate (); LOG.I (TAG, "onCreate");} @SuppressWarnings ("deprecation") @Overridepublic void OnStart (Intent Intent, int startid) {Super.onstart (Intent, Startid); LOG.I (TAG, "OnStart"); Initlocation ();} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {return Super.onstartcommand (Intent, Flags, STA Rtid);} @Overridepublic void OnDestroy () {if (locationclient! = null) {locationclient.stop ();} Super.ondestroy ();} /** * @author Jackie * Baidu map positioning initialization */private void Initlocation () {locationclient = new locationclient (this); LOCATIONCLIENT.R Egisterlocationlistener (this);//Set map positioning callback listener locationclientoption option = new Locationclientoption (); O Ption.setlocationmode (locationmode.hight_accuracy);//SetBit mode hight_accuracy high precision, battery_saving low power, device_sensors device only (GPS) option.setcoortype ("gcj02");//Return of the positioning result is Baidu latitude and longitude, Default value gcj02 latitude coordinate system gcj02, Baidu Mercator coordinate system bd09, Baidu latitude and longitude coordinate system bd09lloption.setisneedaddress (TRUE);//The positioning result returned contains address information// Option.setscanspan (5000);//Set the time interval for initiating a location request to 5000ms not set or set a value less than 1000ms the identity is only positioned once//option.setneeddevicedirect (true);// The returned positioning results include the direction of the phone head locationclient.setlocoption (option); Locationclient.start ();} @Overridepublic void Onreceivelocation (bdlocation location) {if (null = = location) {if (bdlocation! = null) {bdlocation = null;} LOG.D (TAG, "Locate failed: location is null"); return;} /** * 61:gps positioning result *62: Scan consolidation location based failure. The positioning result is not valid at this time. *63: Network exception, the request was not successfully initiated to the server. The positioning result is not valid at this time. *65: The result of locating the cache. *66: Offline targeting results. The corresponding return result when called by Requestofflinelocaiton *67: Offline location failed. *68: When a network connection fails, find the corresponding return result *161: Indicates the network location result *162~167: Server location failed *502:key parameter error * Requestofflinelocaiton 505:key does not exist or illegal *601:key service is disabled by the developer itself *602:key Mcode mismatch *501~700:key authentication failed */int code = Location.getloctype (); if (code = = 161) { this.bdlocation = location; String City = LocatiOn.getcity ();d ouble latitude = location.getlatitude ();d ouble lontitude = Location.getlongitude (); String address = Location.getaddrstr (); LOG.D (TAG, "City" + City + ", (latitude,lontitude) (" + Latitude + "," + Lontitude + "), address" + address "; requestweathe R ();} else {if (bdlocation! = null) {bdlocation = null;} LOG.D (TAG, "Location failed: code=" + code);}}  /** * * @author Jackie * Get weather * * @param view */@SuppressLint ("Handlerleak") private void Requestweather () {final Handler MyHandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {if (msg = = null) {return;} Jsonobject object = (jsonobject) msg.obj;try {int code = object.getint ("error"); String states = Object.getstring ("status"), if (code = = 0 && states.equals ("Success")) {Jsonarray results = object. Getjsonarray ("results"); Jsonobject resultobj = results.getjsonobject (0); Jsonarray Weatherarray = Resultobj.getjsonarray ("Weather_data"); Jsonobject weatherobj = weatherarray.getjsonobject (0); String Daypictureurl = WEATHEROBJ.GEtstring ("Daypictureurl"); String Nightpictureurl = weatherobj.getstring ("Nightpictureurl"),//todo increases daytime, night judgment int tag = dateutil.judgeamorpm (); if (tag = = 0) {//AM Getweatherbitmap (daypictureurl);} else {//PM Getweatherbitmap (nightpictureurl);}} else {log.d (TAG, "weather info get failed, code=" + code);}} catch (Jsonexception e) {log.d (TAG, "Weather information JSON parsing error"); E.printstacktrace ();} Super.handlemessage (msg);}}; New Thread (New Runnable () {public void run () {jsonobject result = Getweatherjson (); Message msg = Message.obtain (); msg.obj = Result;myhandler.sendmessage (msg);} Private Jsonobject Getweatherjson () {//TODO location Gets a successful call to Requestweather so there is no location empty case of String city = Bdlocation.getcity (), if (City.contains ("City")) {City.replace ("City", "");} Patchwork Baidu weather request complete Urlstringbuffer URL = new StringBuffer (); Url.append (GetString (R.string.url_weather)); Url.append (city) ; Url.append ("&output=json&ak="); Url.append (GetString (R.string.baidu_server_key)); return Httputil.getjsonobjectresult (url.tostring (), null);}}). Start ();} /*** Get image URL corresponding to bitmap * @return */@SuppressLint ("Handlerleak") private void Getweatherbitmap (final String URL) {Final Handle R MyHandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {if (msg = = null) {return;} Weatherbitmap = (Bitmap) msg.obj; LOG.D (TAG, "Weatherbitmap convert ok!"); Mergebitmap (); Super.handlemessage (msg); Stopself ();}}; New Thread (New Runnable () {public void run () {Bitmap Bitmap = imageutil.getnetimage (URL, 1); Message msg = Message.obtain (); msg.obj = Bitmap;myhandler.sendmessage (msg);}}). Start ();} Private String FileName = "Location_weather.jpg";/** * combined weather, location for bitmap * @param bitmap * @param str * @return */private B Itmap Mergebitmap () {if (bdlocation = = NULL && Weatherbitmap = = null) {return null;} Bitmap Mergebitmap = null;if (bdlocation! = NULL && Weatherbitmap! = null) {Mergebitmap = imageutil.mergebitmap (th is, Weatherbitmap, Textutils.isempty (Bdlocation.getaddrstr ())? ": Bdlocation.getaddrstr ());} else if (bdlocation! = null) {Mergebitmap= Imageutil.convertfontbitmap (This, Textutils.isempty (Bdlocation.getaddrstr ())? ": Bdlocation.getaddrstr ());} Save operation//string FilePath = Fileutil.savebitmap (FileName, Mergebitmap); String FilePath = Fileutil.savebitmap (FileName, mergebitmap);//intent Intent = new Intent (getString (r.string.location_ Receiver);//intent.putextra ("Mergebitmap", Mergebitmap);//intent.putextra ("filename", filename);// Getapplication (). Sendbroadcast (Intent); Sharedpreferences msharedpreferences = getsharedpreferences ("Real_video_camera", 0); Sharedpreferences.editor meditor = Msharedpreferences.edit ();        Meditor.putstring (GetString (R.string.key_location_file_path), FilePath);                  Meditor.commit (); LOG.D (TAG, "Mergebitmap OK"); return mergebitmap;}}



Get location and weather information with Baidu SDK

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.