package com.mopa.LocationMe;import java.io.BufferedReader;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Locale;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;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.json.JSONArray;import org.json.JSONObject;import android.app.Activity;import android.app.ProgressDialog;import android.content.Context;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Looper;import android.telephony.TelephonyManager;import android.telephony.gsm.GsmCellLocation;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.RelativeLayout;import android.widget.RelativeLayout.LayoutParams;import android.widget.TextView;public class LocationMe extends Activity {    /**     * mTxtLocal显示结果     * mLocalOkListener接口对象的引用     * mProgressDialog进度条     * HttpClient,HttpParams     * timeout超时设置     */    private             TextView mTxtLocal=null;    private             OnGetLocalOkListener mLocalOkListener=null;    private             ProgressDialog mProgressDialog = null;    private             HttpClient httpclient;      private             HttpParams httpParameters;      private             int timeoutConnection = 3000;      private             int timeoutSocket = 5000;        @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //布局        RelativeLayout mRlayout=new RelativeLayout(this);        LayoutParams params=new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);        params.addRule(RelativeLayout.ALIGN_PARENT_TOP);        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);        Button mBtnGetLocal=new Button(this);        mBtnGetLocal.setText("Get Me-Location.");        mRlayout.addView(mBtnGetLocal,params);        mBtnGetLocal.setId(11);        //设置onClickListener监听事件        mBtnGetLocal.setOnClickListener(mOnClickListener);        params=new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);        params.addRule(RelativeLayout.BELOW,11);        mTxtLocal=new TextView(this);        mRlayout.addView(mTxtLocal,params);        setContentView(mRlayout);    }    //监听对象,这里是个匿名内部类.    private OnClickListener mOnClickListener=new OnClickListener() {                @Override        public void onClick(View v) {            // TODO Auto-generated method stub            getItude();        }//end onClick;    };    //通过经纬度获取地理信息    private void getLocalByItude(String latitude,String longitude)    {        HttpURLConnection conn = null;        String line=null;        try {                        URL url=new URL("http://maps.google.cn/maps/geo?key=abcdefg&q="                    + latitude + "," + longitude);            conn = (HttpURLConnection) url.openConnection();            conn.setDoInput(true);            conn.setDoOutput(true);            conn.setUseCaches(false);            conn.setConnectTimeout(timeoutConnection);            conn.setReadTimeout(timeoutSocket);            conn.setRequestMethod("GET");            InputStream inputStream=conn.getInputStream();            InputStreamReader inStreamReader=new InputStreamReader(inputStream,"utf-8");            BufferedReader bufReader=new BufferedReader(inStreamReader);            StringBuffer bufStr=new StringBuffer();                        while((line=bufReader.readLine())!=null)            {                bufStr.append(line);            }            line=bufStr.toString();            if(line!=null&&line.length()>0)            {                JSONObject jsonobject = new JSONObject(line);                JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark")                        .toString());                line="";                for (int i = 0; i < jsonArray.length(); i++) {                   line=jsonArray.getJSONObject(i).getString("address");                }                //回调                mLocalOkListener.onGetOk(line);                        }        } catch (Exception e) {            // TODO: handle exception            mLocalOkListener.onGetOk("");        }        finally{            if(conn!=null)            {                conn.disconnect();                mLocalOkListener.onGetOk(line);            }        }    }    //获得主线程的Handler    private Handler mHandler=new Handler(Looper.getMainLooper());    private void getItude()    {        mProgressDialog = new ProgressDialog(this);        mProgressDialog.setMessage("正在获取中...");        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);        mProgressDialog.show();        //匿名内部类,回调调用的函数        this.setOnGetLocalOkListener(new OnGetLocalOkListener() {                @Override                public void onGetOk(String local) {                    // TODO Auto-generated method stub                    final String mlocal=local;                    mHandler.post(new Runnable() {                                                @Override                        public void run() {                            // TODO Auto-generated method stub                            if(mlocal.length()>0)                            {                                mTxtLocal.setText(mlocal);                                System.out.println("onGetOk........");                                new Thread(new Runnable() {                                                                        @Override                                    public void run() {                                        // TODO Auto-generated method stub                                        saveLocal(mlocal);                                    }                                }).start();                                mProgressDialog.dismiss();                                                            }                            else                            {                                mTxtLocal.setText("获取位置失败,请检查网络是否开启");                                mProgressDialog.dismiss();                            }                                                    }                    });                                    }        });        //开启新的线程去获取经纬度        new Thread(new Runnable() {                        @Override            public void run() {                // TODO Auto-generated method stub                TelephonyManager mTelNet = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);                String operator=mTelNet.getNetworkOperator();                String mcc=operator.substring(0,3);                String mnc=operator.substring(3);                GsmCellLocation location=(GsmCellLocation)mTelNet.getCellLocation();                int cid=location.getCid();                int lac=location.getLac();                httpParameters = new BasicHttpParams();                HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);                HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);                  httpclient = new DefaultHttpClient(httpParameters);                 HttpPost post=new HttpPost("http://www.google.com/loc/json");                try {                    JSONObject holder=new JSONObject();                    holder.put("version", "1.1.0");                    holder.put("host","maps.google.com");                    holder.put("address_language", "zh_CN");                    holder.put("request_address", true);                                        JSONObject tower=new JSONObject();                    tower.put("mobile_country_code", mcc);                    tower.put("mobile_network_code", mnc);                    tower.put("cell_id", cid);                    tower.put("location_area_code", lac);                                        JSONArray towerarray=new JSONArray();                    towerarray.put(tower);                                        holder.put("cell_towers", towerarray);                                        StringEntity query=new StringEntity(holder.toString());                    post.setEntity(query);                    HttpResponse response=httpclient.execute(post);                    HttpEntity entity=response.getEntity();                    BufferedReader buffReader=new BufferedReader(new InputStreamReader(entity.getContent()));                    StringBuffer strBuff=new StringBuffer();                    String result=null;                    while((result=buffReader.readLine())!=null)                    {                        strBuff.append(result);                    }                    JSONObject json=new JSONObject(strBuff.toString());                    JSONObject subjosn=new JSONObject(json.getString("location"));                    getLocalByItude(subjosn.getString("latitude"),subjosn.getString("longitude"));                } catch (Exception e) {                    // TODO: handle exception                    mLocalOkListener.onGetOk("");                }                finally{                    post.abort();                    httpclient=null;                }                            }        }).start();    }    FileWriter mFileWriter=null;    //写文件,保存刚才获取成功的地理位置    public void saveLocal(String local)    {        // TODO Auto-generated method stub        try         {            String strFiles=Environment.getExternalStorageDirectory().toString()+"/Local/";            File outDir=new File(strFiles);            File outFile=new File(strFiles+"LocalMe.txt");            if(outDir.exists()==false)            {                outDir.mkdirs();            }            System.out.println(outFile.getAbsolutePath());            if(outFile.exists()==false)            {                System.out.println("outFile.exists()==false");                outFile.createNewFile();              }            System.out.println(outFile.getAbsolutePath());                        mFileWriter=new FileWriter(outFile,true);            //加入日期            Date date = new Date();            SimpleDateFormat sDataForamat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);            String strTime = sDataForamat.format(date);                mFileWriter.write(strTime+":"+local+"\n");            } catch (IOException e) {            // TODO: handle exception            e.printStackTrace();        }finally        {            if(mFileWriter!=null)                {                    try                     {                        mFileWriter.close();                    } catch (IOException e2)                    {                        // TODO: handle exception                    }                }                            }    }    //设置监听类的引用对象    public void setOnGetLocalOkListener(OnGetLocalOkListener listener)    {        mLocalOkListener = listener;    }    //监听类接口    public interface OnGetLocalOkListener    {        void onGetOk(String local);    }}


Android 基于GeolocationAPI的基站定位

来源:http://www.cnblogs.com/patui/archive/2011/09/10/2173434.html

更多相关文章

  1. Android 高德地图点击地图获取经纬度
  2. Android原生方式获取经纬度和城市信息
  3. Android 基本属性绘制文本对象FontMetrics介绍
  4. android Activity之间传递对象
  5. FregClient进程,创建一个BpFregService类型的代理对象
  6. android XMl 解析神奇xstream 三: 把复杂对象转换成 xml
  7. Android中一个Activity调用另一个Activity — Intent对象的使用
  8. Android获取经纬度
  9. android页面间传递对象

随机推荐

  1. Android之TextView
  2. Android 打开本地文件兼容7.0
  3. 界面开发中布局属性全面剖析
  4. Android的SQLite----重新认识Android(10)
  5. 7715平台修改BUG记录
  6. Android消息处理机制(二)
  7. android sdk+MyEclipse+adt 配置与开发
  8. Android图形显示系统——一张图片的显示
  9. Android 模拟器几个小问题
  10. android 资源之 color