小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Android獲取當前的城市名的方法

 JUST SO LAZY 2013-05-24

Android獲取當前的城市名的方法

Android進階篇-百度地圖獲取地理信息

Android中獲取用戶的地理信息的方式有很多種,各有各得優(yōu)點和缺點。

這里主要介紹的方法是通過調用百度提供的地圖API獲取用戶的地理位置信息。

首要不可缺少的還是百度提供的標準Application類

復制代碼
public class BMapApiApplication extends Application {
    
    public static BMapApiApplication mDemoApp;
    
    public static float mDensity;
    
    //百度MapAPI的管理類
    public BMapManager mBMapMan = null;
    
    // 授權Key
    // TODO: 請輸入您的Key,
    // 申請地址:http://dev.baidu.com/wiki/static/imap/key/
    public String mStrKey = "F9FBF9FAA9BA37C0C6085BD280723A659EC51B20";
    public boolean m_bKeyRight = true;    // 授權Key正確,驗證通過
    
    // 常用事件監(jiān)聽,用來處理通常的網絡錯誤,授權驗證錯誤等
    public static class MyGeneralListener implements MKGeneralListener {
        @Override
        public void onGetNetworkState(int iError) {
            Toast.makeText(BMapApiApplication.mDemoApp.getApplicationContext(), "您的網絡出錯啦!",
                    Toast.LENGTH_LONG).show();
        }

        @Override
        public void onGetPermissionState(int iError) {
            if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
                // 授權Key錯誤:
                Toast.makeText(BMapApiApplication.mDemoApp.getApplicationContext(), 
                        "請在BMapApiDemoApp.java文件輸入正確的授權Key!",
                        Toast.LENGTH_LONG).show();
                BMapApiApplication.mDemoApp.m_bKeyRight = false;
            }
        }
        
    }
    
    @Override
    public void onCreate() {
        mDemoApp = this;
        mBMapMan = new BMapManager(this);
        mBMapMan.init(this.mStrKey, new MyGeneralListener());
        
        mDensity = getResources().getDisplayMetrics().density;
        
        super.onCreate();
    }
    
    @Override
    //建議在您app的退出之前調用mapadpi的destroy()函數,避免重復初始化帶來的時間消耗
    public void onTerminate() {
        // TODO Auto-generated method stub
        if (mBMapMan != null) {
            mBMapMan.destroy();
            mBMapMan = null;
        }
        super.onTerminate();
    }

}
復制代碼

然后是通過注冊百度地圖調用相應的接口獲取經緯度獲取相應的信息

復制代碼
/** Called when the activity is first created. */
    /** 上下文 */
    private BMapApiApplication mApplication;
    /** 定義搜索服務類 */
    private MKSearch mMKSearch;
    
    /** 記錄當前經緯度的MAP*/
    private HashMap<String, Double> mCurLocation = new HashMap<String, Double>();
    //城市名
    private String cityName;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mApplication = (BMapApiApplication) this.getApplication();
        if (mApplication.mBMapMan == null) {
            mApplication.mBMapMan = new BMapManager(getApplication());
            mApplication.mBMapMan.init(mApplication.mStrKey,
                    new BMapApiApplication.MyGeneralListener());
        }
        
        /** 初始化MKSearch */
        mMKSearch = new MKSearch();
        mMKSearch.init(mApplication.mBMapMan, new MySearchListener());
    }
    
    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        this.registerLocationListener();
    }

    private void registerLocationListener() {
        mApplication.mBMapMan.getLocationManager().requestLocationUpdates(
                mLocationListener);
        if (mApplication.mBMapMan != null) {
            /** 開啟百度地圖API */
            mApplication.mBMapMan.start();
        }
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        this.unRegisterLocationListener();
    }

    private void unRegisterLocationListener() {
        mApplication.mBMapMan.getLocationManager().removeUpdates(
                mLocationListener);
        if (mApplication.mBMapMan != null) {
            /** 終止百度地圖API */
            mApplication.mBMapMan.stop();
        }
    }

    @Override
    protected void onDestroy() {
        if (mApplication.mBMapMan != null) {
            /** 程序退出前需調用此方法 */
            mApplication.mBMapMan.destroy();
            mApplication.mBMapMan = null;
        }
        super.onDestroy();
    }

    /** 注冊定位事件 */
    private LocationListener mLocationListener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            if (location != null) {
                try {
                    int longitude = (int) (1000000 * location.getLongitude());
                    int latitude = (int) (1000000 * location.getLatitude());

                    /** 保存當前經緯度 */
                    mCurLocation.put("longitude", location.getLongitude());
                    mCurLocation.put("latitude", location.getLatitude());

                    GeoPoint point = new GeoPoint(latitude, longitude);
                    /** 查詢該經緯度值所對應的地址位置信息 */
                    Weather_WelcomeActivity.this.mMKSearch
                            .reverseGeocode(new GeoPoint(latitude, longitude));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /** 內部類實現MKSearchListener接口,用于實現異步搜索服務 */
    private class MySearchListener implements MKSearchListener {
        @Override
        public void onGetAddrResult(MKAddrInfo result, int iError) {
            if( iError != 0 || result == null){
                Toast.makeText(Weather_WelcomeActivity.this, "獲取地理信息失敗", Toast.LENGTH_LONG).show();
            }else {
                Log.info("json", "result= " + result);
                cityName =result.addressComponents.city;
                Bundle bundle = new Bundle();
                bundle.putString("cityName", cityName.substring(0, cityName.lastIndexOf("")));
                Intent intent = new Intent(Weather_WelcomeActivity.this,Weather_MainActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
                Weather_WelcomeActivity.this.finish();
            }
        }

        @Override
        public void onGetDrivingRouteResult(MKDrivingRouteResult result,
                int iError) {
        }

        @Override
        public void onGetPoiResult(MKPoiResult result, int type, int iError) {
        }

        @Override
        public void onGetTransitRouteResult(MKTransitRouteResult result,
                int iError) {
        }

        @Override
        public void onGetWalkingRouteResult(MKWalkingRouteResult result,
                int iError) {
        }
    }
復制代碼

其他方式獲取當前的城市名:

復制代碼
/**
     * 抓取當前的城市信息
     * 
     * @return String 城市名
     */
    public String getCurrentCityName(){
        String city = "";
        TelephonyManager telManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        GsmCellLocation glc = (GsmCellLocation) telManager.getCellLocation();
        
        if (glc != null){
            int cid = glc.getCid(); // value 基站ID號
            int lac = glc.getLac();// 寫入區(qū)域代碼
            String strOperator = telManager.getNetworkOperator();
            int mcc = Integer.valueOf(strOperator.substring(0, 3));// 寫入當前城市代碼
            int mnc = Integer.valueOf(strOperator.substring(3, 5));// 寫入網絡代碼
            String getNumber = "";
            getNumber += ("cid:" + cid + "\n");
            getNumber += ("cid:" + lac + "\n");
            getNumber += ("cid:" + mcc + "\n");
            getNumber += ("cid:" + mnc + "\n");
            DefaultHttpClient client = new DefaultHttpClient();
            BasicHttpParams params = new BasicHttpParams();
            HttpConnectionParams.setSoTimeout(params, 20000);
            HttpPost post = new HttpPost("http://www.google.com/loc/json");
            
            try{
                JSONObject jObject = new JSONObject();
                jObject.put("version", "1.1.0");
                jObject.put("host", "maps.google.com");
                jObject.put("request_address", true);
                if (mcc == 460)
                    jObject.put("address_language", "zh_CN");
                else
                    jObject.put("address_language", "en_US");

                JSONArray jArray = new JSONArray();
                JSONObject jData = new JSONObject();
                jData.put("cell_id", cid);
                jData.put("location_area_code", lac);
                jData.put("mobile_country_code", mcc);
                jData.put("mobile_network_code", mnc);
                jArray.put(jData);
                jObject.put("cell_towers", jArray);
                StringEntity se = new StringEntity(jObject.toString());
                post.setEntity(se);

                HttpResponse resp = client.execute(post);
                BufferedReader br = null;
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                    br = new BufferedReader(new InputStreamReader(resp
                            .getEntity().getContent()));
                    StringBuffer sb = new StringBuffer();

                    String result = br.readLine();
                    while (result != null){
                        sb.append(getNumber);
                        sb.append(result);
                        result = br.readLine();
                    }
                    String s = sb.toString();
                    s = s.substring(s.indexOf("{"));
                    JSONObject jo = new JSONObject(s);
                    JSONObject arr = jo.getJSONObject("location");
                    JSONObject address = arr.getJSONObject("address");
                    city = address.getString("city");
                }
            }
            catch (JSONException e){
                e.printStackTrace();
            }
            catch (UnsupportedEncodingException e){
                e.printStackTrace();
            }
            catch (ClientProtocolException e){
                e.printStackTrace();
            }
            catch (IOException e){
                e.printStackTrace();
            }
            finally{
                post.abort();
                client = null;
            }
        }
        return city;
    }
復制代碼

 加入這兩個權限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    本站是提供個人知識管理的網絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯系方式、誘導購買等信息,謹防詐騙。如發(fā)現有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約