GPS定位获取位置,获取天气

注:清单文件中要加上权限
一般我把常用权限都加上了,AndroidManifest.xml
 
    
    
    
    
    
    
    
    

    
    

    
    

    
    

    
    

    
    
    

    
    

    
    
    

    
    

    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    

    


 
  
窗体代码
public class MainActivity extends Activity {

	private TextView txt1,txt2,txt3;
	private String city;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        //获取控件
        findView();
        //获取数据
        getData();
    }


    private void getData() {

		// 定义LocationManager对象
		LocationManager locationManager;
		// 获取系统LocationManager服务
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// 从GPS获取最近的定位信息
		Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		
		try{
			
			location.setAccuracy(20);
		}catch(Exception e){
			
		}
//		String coordinate;  
		String lng = "";
		String lat = "";
		try {

			//未纠偏的坐标
			double dLng=location.getLongitude();//经度
			double dLat=location.getLatitude();//纬度
			
			//地球坐标转火星坐标
			Map localMap= GPSModify.transform(dLng,dLat);
			
			//纠偏
			lng=localMap.get("lon")+"";			
			lat=localMap.get("lat")+"";	
			
			txt1.setText("经度"+lng);
			txt2.setText("纬度"+lat);
//			 coordinate = "Latitude:" + lat + "\nLongitude:" + lng;
			
	        double longitude = Double.valueOf(lng);  
	        double latitude = Double.valueOf(lat); 
	        
	        //通过经纬度获取位置
			 Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());  
			
			 List
addresses = geocoder.getFromLocation(latitude, longitude, 1); StringBuilder sb = new StringBuilder(); if (addresses.size() > 0) { Address address = addresses.get(0); // for (int i = 0; i < address.getMaxAddressLineIndex(); i++) { sb.append(address.getAddressLine(0)).append("\n"); // } //获取天气时需要的地区 city= address.getLocality().toString().replace("市", ""); // sb.append(address.getLocality()).append("\n"); // sb.append(address.getCountryName()); //当前位置 String addressStr = sb.toString(); txt3.setText("地址:"+addressStr+"\n天气:" ); //异步加载获取天气 QueryAsyncTask asyncTask = new QueryAsyncTask(); asyncTask.execute(""); // String weather=getWeather("北京"); } } catch (Exception e) { e.printStackTrace(); } } private class QueryAsyncTask extends AsyncTask { @Override protected void onPostExecute(Object result) { try { if (result != null) { String weatherResult = (String) result; if (weatherResult.split(";").length > 1) { String a = weatherResult.split(";")[1]; if (a.split("=").length > 1) { String b = a.split("=")[1]; String c = b.substring(1, b.length() - 1); String[] resultArr = c.split("\\}"); if (resultArr.length > 0) { todayParse(resultArr[0]); System.out.println(resultArr[1]); /* * tommrowParse(resultArr[1]); * thirddayParse(resultArr[2]); * ll_yes.setVisibility(View.VISIBLE); // * tv_city.setText(cityName); * tv_city.setText(districtName); */ // tv_address.setText(districtName); } } else { } } else { } } else { } } catch (Exception e) { // TODO: handle exception } super.onPostExecute(result); } @Override protected Object doInBackground(Object... params) { // return HttpService.getWeather(districtName); return getWeather(city); } } /** * * 方法名:todayParse 功能:今天天气 参数: * * @param weather */ private void todayParse(String weather) { System.out.println(weather); String temp = weather.replace("'", ""); String[] tempArr = temp.split(","); String wd = ""; String tq = ""; String fx = ""; if (tempArr.length > 0) { for (int i = 0; i < tempArr.length; i++) { System.out.println(tempArr[i]); if (tempArr[i].indexOf("t1:") != -1) { wd = tempArr[i].substring(3, tempArr[i].length()) + "℃"; } else if (tempArr[i].indexOf("t2:") != -1) { wd = tempArr[i].substring(3, tempArr[i].length()) + "℃"+ "~"+wd; ; } else if (tempArr[i].indexOf("d1:") != -1) { fx = tempArr[i].substring(3, tempArr[i].length()); } else if (tempArr[i].indexOf("s1:") != -1) { tq = tempArr[i].substring(4, tempArr[i].length()); } } // tv_wd.setText("气温:" + wd); // tv_tq.setText("天气情况:" + tq); // // tv_attr3.setText("风向:" + fx); String txt=txt3.getText().toString(); txt3.setText(txt+tq+"\n"+wd+" "+fx); } }
//根据城市来获取天气
    public static String getWeather(String city) {
		String result = null;
		String url = "http://php.weather.sina.com.cn/iframe/index/w_cl.php?code=js&day=2&city="
				+ city + "&dfc=3";
		try {
			DefaultHttpClient client = getDefaultHttpClient2();
			HttpGet mothod = new HttpGet(url);
			
			HttpResponse httpResponse = client.execute(mothod);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(httpResponse.getEntity(),
						"gb2312");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			// JavaUtil.ShowDialog(WeatherScreen.this,
			// "查无天气信息",getLayoutInflater(),getWindowManager());
		} finally {
			return result;
		}

	}
    
    private static DefaultHttpClient getDefaultHttpClient2() {
		DefaultHttpClient client;
		HttpParams httpParams = new BasicHttpParams();
		// 设置代理
		String host = android.net.Proxy.getDefaultHost();
		int port = android.net.Proxy.getDefaultPort();
		// Log.v(TAG,"代理:"+host+",端口:"+port);
		if (host != null) {
			HttpHost httpHost = new HttpHost(host, port);
			httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, httpHost);
		}
		// 设置超时
		HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
		HttpConnectionParams.setSoTimeout(httpParams, 20000);

		SchemeRegistry schReg = new SchemeRegistry();
		schReg.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		schReg.register(new Scheme("https",
				SSLSocketFactory.getSocketFactory(), 443));

		// 使用线程安全的连接管理来创建HttpClient
		ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
				httpParams, schReg);
		client = new DefaultHttpClient(conMgr, httpParams);

		return client;
	}


	private void findView() {
    	txt1=(TextView) this.findViewById(R.id.txt1);
    	txt2=(TextView) this.findViewById(R.id.txt2);
    	txt3=(TextView) this.findViewById(R.id.txt3);
		
	}

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    
}

你可能感兴趣的:(Android)