定位、列表展示
1、定位城市并展示列表信息
package com.bwie.fuxi_yuekao; import java.util.List; import android.app.Activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import com.baidu.location.Address; 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.baidu.mapapi.SDKInitializer; import com.bwie.adapter.MyAdapter; import com.bwie.utils.MyUtils; import com.bwie.vo.XmlBean; import com.bwie.vo.XmlBean.Myitem; import com.thoughtworks.xstream.XStream; public class MainActivity extends Activity { private String URL = "http://apis.juhe.cn/goodbook/catalog?key=9d6ef8c31647a206e05fcaff70527182&dtype=xml"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 在使用SDK各组件之前初始化context信息,传入ApplicationContext // 注意该方法要再setContentView方法之前实现 SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); //找控件 init(); // 声明locationclient对象 locationClient = new LocationClient(getApplicationContext()); // 注册监听函数 locationClient.registerLocationListener(bdlisten); // 设置定位的参数 initLocation(); // 开始定位 locationClient.start(); // 请求网络数据 new MyAsyn().execute(URL); } private void init() { // TODO Auto-generated method stub lv = (ListView) findViewById(R.id.lv); tv_city = (TextView) findViewById(R.id.tv_city); } class MyAsyn extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub //请求网络数据 String webdata = MyUtils.getWebColumn(params[0]); System.out.println(webdata+"============"); return webdata; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); //获取请求的数据 XStream xStream = new XStream(); xStream.processAnnotations(XmlBean.class); XmlBean fromXML = (XmlBean) xStream.fromXML(result); final List<Myitem> item = fromXML.result.item; //为lv设置适配器 lv.setAdapter(new MyAdapter(MainActivity.this, item)); //为lv设置条目点击监听事件 lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub Intent intent=new Intent(MainActivity.this,InfoActivity.class); intent.putExtra("id", item.get(position).id); startActivity(intent); } }); } } BDLocationListener bdlisten = new BDLocationListener() { @Override public void onReceiveLocation(BDLocation arg0) { // TODO Auto-generated method stub // 获取定位的位置 String address = arg0.getStreet(); double latitude = arg0.getLatitude(); String city = arg0.getCity(); tv_city.setText("定位城市:"+city); Log.i("TAG", city + "================"); } }; private LocationClient locationClient; private ListView lv; private TextView tv_city; private void initLocation() { LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationMode.Hight_Accuracy);// 可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 option.setCoorType("bd09ll");// 可选,默认gcj02,设置返回的定位结果坐标系 int span = 1000; option.setScanSpan(span);// 可选,默认0,即仅定位一次,设置发起定位请求的间隔需要大于等于1000ms才是有效的 option.setIsNeedAddress(true);// 可选,设置是否需要地址信息,默认不需要 option.setOpenGps(true);// 可选,默认false,设置是否使用gps option.setLocationNotify(true);// 可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 option.setIsNeedLocationDescribe(true);// 可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” option.setIsNeedLocationPoiList(true);// 可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 option.setIgnoreKillProcess(false);// 可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 option.SetIgnoreCacheException(false);// 可选,默认false,设置是否收集CRASH信息,默认收集 option.setEnableSimulateGps(false);// 可选,默认false,设置是否需要过滤gps仿真结果,默认需要 locationClient.setLocOption(option); } }
展示对应类型图书的信息
package com.bwie.fuxi_yuekao; import java.util.ArrayList; import java.util.List; import android.R.bool; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.text.format.DateUtils; import android.util.Log; import android.view.KeyEvent; import android.widget.GridView; import android.widget.Toast; import com.bwie.adapter.MyAda_info; import com.bwie.utils.MyUtils; import com.bwie.vo.MyData; import com.bwie.vo.SuperClass; import com.google.gson.Gson; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2; import com.handmark.pulltorefresh.library.PullToRefreshGridView; public class InfoActivity extends Activity { private PullToRefreshGridView gv; private boolean isExit=false; private String Url = "http://apis.juhe.cn/goodbook/query?key=9d6ef8c31647a206e05fcaff70527182"; int req = 1; int load = 1; private String id; Handler handler = new Handler() { public void handleMessage(android.os.Message msg) { if(msg.what == 1) { List<MyData> list = (List<MyData>) msg.obj; // 为handler设置适配器 gv.setAdapter(new MyAda_info(InfoActivity.this, list)); } if(msg.what == 0) { isExit = false; } }; }; private ArrayList<MyData> dlist; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_info); dlist = new ArrayList<MyData>(); // 获取跳转传来的值 Intent intent = getIntent(); id = intent.getStringExtra("id"); // 得到控件 gv = (PullToRefreshGridView) findViewById(R.id.pull_refresh_grid); // 请求网络数据 reqData(Url, req, id); // 实现上拉加载、下拉刷新的功能 gv.setOnRefreshListener(new OnRefreshListener2<GridView>() { @Override public void onPullDownToRefresh( PullToRefreshBase<GridView> refreshView) { Log.e("TAG", "onPullDownToRefresh"); // Do work to String label = DateUtils.formatDateTime( getApplicationContext(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL); // Update the LastUpdatedLabel refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label); // 请求网络数据 reqData(Url, req, id); // 取消刷新 gv.onRefreshComplete(); } @Override public void onPullUpToRefresh( PullToRefreshBase<GridView> refreshView) { Log.e("TAG", "onPullUpToRefresh"); // Do work to refresh // the list here. // 请求网络数据 load++; reqData(Url, load, id); // 取消刷新 gv.onRefreshComplete(); } }); } private void reqData(final String url, final int req, final String id) { new Thread() { public void run() { // 请求网络数据 String data = MyUtils.getWebData(url, req, id); // 进行解析json数据 Gson g = new Gson(); SuperClass sc = g.fromJson(data, SuperClass.class); if (sc != null) { List<MyData> list = sc.getResult().getData(); dlist.addAll(list); // 将数据发送给主线程 handler.sendMessage(handler.obtainMessage(1, dlist)); } }; }.start(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exit(); return false; } return super.onKeyDown(keyCode, event); } private void exit() { if (!isExit) { isExit = true; Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show(); // 利用handler延迟发送更改状态信息 handler.sendEmptyMessageDelayed(0, 2000); } else { finish(); System.exit(0); } } }
请求网络数据封装类
package com.bwie.utils; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; public class MyUtils { //获取网络列表 public static String getWebColumn(String URL) { String data =""; //创建请求对象 HttpGet httpGet = new HttpGet(URL); //设置参数 HttpParams params=new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 5000); //执行请求的对象 HttpClient client=new DefaultHttpClient(params); //执行请求镀锡 try { HttpResponse resp = client.execute(httpGet); //判断是否响应成功 if(resp.getStatusLine().getStatusCode() == 200) { //获取响应 的数据 HttpEntity entity = resp.getEntity(); data = EntityUtils.toString(entity, "utf-8"); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return data; } //获取网络列表 public static String getWebData(String URL,int p,String id) { StringBuffer sb=new StringBuffer(URL); sb.append("&catalog_id="+id); sb.append("&pn="+p); String data =""; //创建请求对象 HttpGet httpGet = new HttpGet(sb.toString()); //设置参数 HttpParams params=new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 5000); HttpConnectionParams.setSoTimeout(params, 5000); //执行请求的对象 HttpClient client=new DefaultHttpClient(params); //执行请求镀锡 try { HttpResponse resp = client.execute(httpGet); //判断是否响应成功 if(resp.getStatusLine().getStatusCode() == 200) { //获取响应 的数据 HttpEntity entity = resp.getEntity(); data = EntityUtils.toString(entity, "utf-8"); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return data; } }
解析xml、json文件的Javabean类
package com.bwie.vo; import java.util.List; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamImplicit; @XStreamAlias("root") public class XmlBean { public String resultcode; public String reason; public Myresult result; public String error_code; @XStreamAlias("result") public class Myresult { @XStreamImplicit(itemFieldName = "item") public List<Myitem> item; } public class Myitem { public String id; public String catalog; } }
xml上拉加载,下拉刷新
<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=".InfoActivity" > <!-- The PullToRefreshGridView replaces a standard GridView widget. --> <com.handmark.pulltorefresh.library.PullToRefreshGridView xmlns:ptr="http://schemas.android.com/apk/res-auto" android:id="@+id/pull_refresh_grid" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="100dp" android:gravity="center_horizontal" android:horizontalSpacing="1dp" android:numColumns="auto_fit" android:stretchMode="columnWidth" android:verticalSpacing="1dp" ptr:ptrDrawable="@drawable/ic_launcher" ptr:ptrMode="both" /> </RelativeLayout>
manifestxml中的相关设置
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.bwie.fuxi_yuekao" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="com.android.launcher.permission.READ_SETTINGS" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.GET_TASKS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_SETTINGS" /> <!-- 这个权限用于进行网络定位 --> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" > </uses-permission> <!-- 这个权限用于访问GPS定位 --> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > </uses-permission> <!-- 用于访问wifi网络信息,wifi信息会用于进行网络定位 --> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" > </uses-permission> <!-- 获取运营商信息,用于支持提供运营商信息相关的接口 --> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" > </uses-permission> <!-- 这个权限用于获取wifi的获取权限,wifi信息会用来进行网络定位 --> <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" /> <!-- SD卡读取权限,用户写入离线定位数据 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" > </uses-permission> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <meta-data android:name="com.baidu.lbsapi.API_KEY" android:value="TglpW0F8H0GhNQk55Wjs8KtbLGIrB6dh" /> <activity android:name="com.bwie.fuxi_yuekao.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.location.f" android:enabled="true" android:process=":remote" > </service> <activity android:name="com.bwie.fuxi_yuekao.InfoActivity" android:label="@string/title_activity_info" > </activity> </application> </manifest>