10 days to learn Android-sixth day

Source: Internet
Author: User

After a few days of study, our weather forecast program has been able to show the weather normal, as said before, now the app can only display the fixed area of the weather, then how can we show our own location of the weather?

Android targeting

The Android system itself provides three positioning methods, namely, network, base station and GPS, mainly using Locationmanager, Telephonymanager related class library, but for some reason, Google's API in the domestic visit frequently problems, So here I do not do the introduction of these APIs, there is a need to understand that you can query the relevant information.

Baidu Map Location

In addition to the positioning function provided by Android itself, there are many positioning systems in the country for us to use, such as Baidu Map, the gold map has provided the corresponding functions, I here mainly introduce the use of Baidu map.

Need to http://lbsyun.baidu.com/sdk/download?selected=location download the positioning function of the development package, and then put the contents of the development package into the Libs folder, so we introduced the Baidu Map positioning function API.

Then, let's get started.

Configure Manifest

First add the permissions needed to locate the feature, and remember where to add it.

    <!--this permission for network positioning-<uses-permission android:name= "Android.permission.ACCESS_COARSE_LOCATION"/> & lt;! --this permission is used to access GPS--<uses-permission android:name= "Android.permission.ACCESS_FINE_LOCATION"/> <!--used to visit Ask WiFi information, WiFi information will be used for network positioning-<uses-permission android:name= "Android.permission.ACCESS_WIFI_STATE"/> < !--get carrier information to support the interface that provides carrier information--<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/ > <!--this permission to get access to WiFi, WiFi information is used for network positioning-<uses-permission android:name= "Android.permission.CHANGE_W Ifi_state "/> <!--for reading the current status of the phone--<uses-permission android:name=" Android.permission.READ_PHONE_STATE "/ > <!--Write extended storage, write data to the expansion card for writing offline location data--<uses-permission android:name= "android.permission.WRITE_EXTERNAL_ STORAGE "/> <!--SD card read access, user writes offline location data--<uses-permission android:name=" android.permission.MOUNT_UNMOUNT_ Filesystems "/> <!--Allows the app to read low-level system log files--<uses-permission android:name= "Android.permission.READ_LOGS"/> 

Then, within the application node, add a service that is running in the background to get the targeted services,

        <service            android:name= "com.baidu.location.f"            android:enabled= "true"            android:process= ": Remote" >            <intent-filter>                <action android:name= "com.baidu.location.service_v2.2" >                </ action>            </intent-filter>        </service>

Finally, within the application node, add the accesskey of the Baidu Map API we applied for.

        <meta-data            android:name= "Com.baidu.lbsapi.API_KEY"            android:value= "Ykngmxiopugt7yrnrg955yls"/>

In this way, Baidu map of the introduction even if it is completed. So how do you use it in your code?

To open the Mainactivity.java, we need to refactor the code simply.

You can use the Eclipse refactoring tool, or you can manually modify the code to read as follows:

    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Viewutils.inject (this);        Datas = new arraylist<weatherdatabean> ();        adapter = new Weatheradapter (Getapplicationcontext (), datas);        Lstweather.setadapter (adapter);    GetWeather ("Beijing");        } private void GetWeather (String city) {httputils http = new Httputils ();        Requestparams params = new Requestparams ();        Params.addquerystringparameter ("Location", city);        Params.addquerystringparameter ("Output", "json");        Params.addquerystringparameter ("AK", "ykngmxiopugt7yrnrg955yls"); Http.send (Httpmethod.get, "Http://api.map.baidu.com/telematics/v3/weather", params, new requestcallback<string            > () {@Override public void onsuccess (responseinfo<string> responseinfo) {StrinG weather = Responseinfo.result;                Gson Gson = new Gson ();                data = Gson.fromjson (weather, baidudata.class);                Datas.clear ();                Datas.addall (Data.getresults (). Get (0). Getweather_data ());                Adapter.notifydatasetchanged ();            LOG.V ("Onsuccess", data.tostring ()); } @Override public void OnFailure (HttpException arg0, String arg1) {Log            . V ("OnFailure", arg1);    }        } ); }

Here a new addition to the city as a parameter method GetWeather, after the reconstruction, we added Baidu positioning function.

DECLARE two variables:

    Private Locationclient mlocationclient;    Private Bdlocationlistener MyListener;

Add a method that initializes the two variables,

    private void Initlocationclient ()    {        mlocationclient = new Locationclient (Getapplicationcontext ());         MyListener = new Mylocationlistener ();        locationclientoption option = new Locationclientoption ();        Option.setlocationmode (locationmode.hight_accuracy);        Option.setisneedaddress (true);        mlocationclient.setlocoption (option);        Mlocationclient.registerlocationlistener (MyListener);    }

We are using Mylocationlistener, this class needs to be customized, as the inner class of mainactivity exists,

    public class Mylocationlistener implements Bdlocationlistener    {        @Override public        void Onreceivelocation ( Bdlocation location)        {            String city = location.getcity ();            GetWeather (city);            Settitle (city + "Weather");        }    }

Then, modify the OnCreate method,

    protected void OnCreate (Bundle savedinstancestate)    {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        Viewutils.inject (this);        Datas = new arraylist<weatherdatabean> ();        adapter = new Weatheradapter (Getapplicationcontext (), datas);        Lstweather.setadapter (adapter);        Initlocationclient ();        Mlocationclient.start ();    }

Finally, add the OnStop method,

    @Override    protected void OnStop ()    {        super.onstop ();        Mlocationclient.stop ();    }

Finish the call.

Run it and see how it works, anyway mine is this:

Is it the city where you are located?

Now that you see the effect, explain the above code a little bit.

First, when the interface is loaded, the Initlocationclient method is called, which initializes the function of Locationclient and bdlocationlistener,locationclient to get the location asynchronously. Mylocationlistener is the callback method after the locationclient gets the positioning, we call the method of getting the weather in this callback method GetWeather, and call the Settitle method to modify the app page titled "City Name + weather ”。

The whole process is perfect, just a little bit worse.

Where is this point?

Is that we need to locate each time we get the weather, and you don't change the city every day, so our program needs to be optimized. The optimized process is:

1. Read the city from the local, and also call Baidu location

2. If the local city in 1 is not empty, get the weather

3. If the city of Baidu in 1 is aligned with the local city, it will not get the weather again; if not, cover the local city and get the weather back.

There are two benefits to this:

1. Only the first time the app is launched, the local city is empty, then it is faster to get the weather

2. Even if the city has been replaced, it can accurately respond to

Now that you have organized your ideas, let's get started.

There are several ways to store data on the Android, mainly preference, Sqlite, file Three, we are using preference this way today.

Preference

Preference is suitable for storing lightweight data, such as String, Int, Boolean, and so on, the city data we need to save is a simple string that is well suited to this approach.

Add two methods in Mainactivity.java, respectively, to store and read data.

    private void Savecity (String city)    {        sharedpreferences sharedpreferences = getsharedpreferences ("Weather", Context.mode_private);        Editor editor = Sharedpreferences.edit ();        Editor.putstring ("City", city);        Editor.commit ();    }    Private String readcity ()    {        sharedpreferences sharedpreferences = getsharedpreferences ("Weather", Context.mode_private);        Return sharedpreferences.getstring ("City", "");    }

Some experienced programmers can see at a glance that data is stored in the form of key/value in preference.

Then modify the OnCreate method,

    protected void OnCreate (Bundle savedinstancestate)    {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        Viewutils.inject (this);        Datas = new arraylist<weatherdatabean> ();        adapter = new Weatheradapter (Getapplicationcontext (), datas);        Lstweather.setadapter (adapter);        Initlocationclient ();        Mlocationclient.start ();        String city = readcity ();        if (city = null && city.length () > 0)        {            getWeather (city);        }    }

This adds the logic to read the local city and get the weather.

Next modify the Mylocationlistener,

    public class Mylocationlistener implements Bdlocationlistener    {        @Override public        void Onreceivelocation ( Bdlocation location)        {            String city = location.getcity ();            String localcity = readcity ();            if (!localcity.equals)            {                savecity (city);                GetWeather (city);}}    }

This adds the logic of locating the city and local city judgments, and deletes the call to the Settitle method.

Finally, modify the GetWeather method to add a call to Settitle on the first line of the method.

Settitle (city + "weather");

After finishing the call, the last Mainactivity.java is like this:

public class Mainactivity extends activity{@ViewInject (r.id.weather_list) private ListView lstweather;    Private Weatheradapter adapter;    Private baidudata data;    Private list<weatherdatabean> datas;    Private Locationclient mlocationclient;    Private Bdlocationlistener MyListener;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Viewutils.inject (this);        Datas = new arraylist<weatherdatabean> ();        adapter = new Weatheradapter (Getapplicationcontext (), datas);        Lstweather.setadapter (adapter);        Initlocationclient ();        Mlocationclient.start ();        String city = readcity ();        if (city = null && city.length () > 0) {getWeather (city);        }} private void GetWeather (String city) {settitle (city + "weather");  Httputils http = new Httputils ();      Requestparams params = new Requestparams ();        Params.addquerystringparameter ("Location", city);        Params.addquerystringparameter ("Output", "json");        Params.addquerystringparameter ("AK", "ykngmxiopugt7yrnrg955yls"); Http.send (Httpmethod.get, "Http://api.map.baidu.com/telematics/v3/weather", params, new requestcallback<string            > () {@Override public void onsuccess (responseinfo<string> responseinfo)                {String weather = Responseinfo.result;                Gson Gson = new Gson ();                data = Gson.fromjson (weather, baidudata.class);                Datas.clear ();                Datas.addall (Data.getresults (). Get (0). Getweather_data ());                Adapter.notifydatasetchanged ();            LOG.V ("Onsuccess", data.tostring ()); } @Override public void OnFailure (HttpException arg0, String arg1) {Log . V ("OnfailuRe ", arg1);    }        } ); } private void Initlocationclient () {mlocationclient = new Locationclient (Getapplicationcontext ());//Declaration L        Ocationclient class MyListener = new Mylocationlistener ();        locationclientoption option = new Locationclientoption ();        Option.setlocationmode (locationmode.hight_accuracy);        Option.setisneedaddress (TRUE);        mlocationclient.setlocoption (option);    Mlocationclient.registerlocationlistener (MyListener);        } @Override protected void OnStop () {super.onstop ();    Mlocationclient.stop (); } public class Mylocationlistener implements Bdlocationlistener {@Override public void Onreceivelocat            Ion (Bdlocation location) {String city = location.getcity ();            String localcity = readcity ();                if (!localcity.equals) {savecity (city);            GetWeather (city);  }        }  } private void Savecity (String city) {sharedpreferences sharedpreferences = getsharedpreferences ("Weath        Er ", context.mode_private);        Editor editor = Sharedpreferences.edit ();        Editor.putstring ("City", city);    Editor.commit (); } private String readcity () {sharedpreferences sharedpreferences = getsharedpreferences ("Weather", Context.        Mode_private);    Return sharedpreferences.getstring ("City", "" "); }}

Today's main task is to embed the Baidu map, refactoring the code, optimize the process, the most important thing is that we learn the use of sharedpreferences, the way to save data in the app is often used, I hope you can master.

Please note that the key used in this article is personal to me and do not use it for any commercial purpose. If there is commercial need, please contact me or apply for accesskey on Baidu website.

The attachment is the project document, click Download Http://pan.baidu.com/s/1jG9puYU.

This series of articles is my original, if need to reprint, please specify the source www.liuzhibang.cn

10 days to learn Android-sixth day

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.