Android實現自動定位城市並獲取天氣信息


定位實現代碼:

<span style="font-size:14px;">import java.io.IOException;
import java.util.List;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class LocationUtils {
	public static String cityName;   //城市名
	private static Geocoder geocoder;  //此對象能通過經緯度來獲取相應的城市等信息
	//通過地理坐標獲取城市名 其中CN分別是city和name的首字母縮寫
	public static void getCNBylocation(Context context){
		geocoder = new Geocoder(context);
		//用於獲取Location對象,以及其他
		LocationManager locationManager;
		String serviceName = Context.LOCATION_SERVICE;
		//實例化一個LocationManager對象
		locationManager = (LocationManager) context.getSystemService(serviceName);
		//provider的類型
		String provider = LocationManager.NETWORK_PROVIDER;
		
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_LOW);    //低精度   高精度:ACCURACY_FINE 
		criteria.setAltitudeRequired(false);       //不要求海拔
		criteria.setBearingRequired(false);       //不要求方位
		criteria.setCostAllowed(false);      //不允許產生資費
		criteria.setPowerRequirement(Criteria.POWER_LOW);   //低功耗
		
		//通過最后一次的地理位置來獲取Location對象
		Location location = locationManager.getLastKnownLocation(provider);
		
		String queryed_name = updateWithNewLocation(location);
		if((queryed_name!=null)&&(0!=queryed_name.length())){
			cityName = queryed_name;
		}
		/*
		第二個參數表示更新的周期,單位為毫秒,
		第三個參數的含義表示最小距離間隔,單位是米,設定每30秒進行一次自動定位
		*/
		locationManager.requestLocationUpdates(provider, 30000, 50, locationListener);
		//移除監聽器,在只有一個widget的時候,這個還是適用的
		locationManager.removeUpdates(locationListener);
	}
	//方位改變是觸發,進行調用
	private final static LocationListener locationListener = new LocationListener() {
		String tempCityName;
		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
		@Override
		public void onProviderEnabled(String provider) {
		}
		@Override
		public void onProviderDisabled(String provider) {
			tempCityName = updateWithNewLocation(null);
			if((tempCityName!=null)&&(tempCityName.length()!=0)){
				cityName = tempCityName;
			}
		}
		@Override
		public void onLocationChanged(Location location) {
			tempCityName = updateWithNewLocation(location);
			if((tempCityName!=null)&&(tempCityName.length()!=0)){
				cityName = tempCityName;
			}
		}
	};
	//更新location  return cityName
	private static String updateWithNewLocation(Location location){
		String mcityName = "";
		double lat = 0;
		double lng = 0;
		List<Address> addList = null;
		if(location!=null){
			lat = location.getLatitude();
			lng = location.getLongitude();
		}else{
			cityName = "無法獲取地理信息";
		}
		try {
			addList = geocoder.getFromLocation(lat, lng, 1);    //解析經緯度
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(addList!=null&&addList.size()>0){
			for(int i=0;i<addList.size();i++){
				Address add = addList.get(i);
				mcityName += add.getLocality();
			}
		}
		if(mcityName.length()!=0){
			return mcityName.substring(0, (mcityName.length()-1));
		}else{
			return mcityName;
		}
	}
}
</span>

<span style="font-size:14px;">public class TargetUrl {
	public final static String url1 = "http://api.map.baidu.com/telematics/v3/weather?location=";
	public final static String url2 = "&output=json&ak=9cCAXQFB468dsH11GOWL8Lx4";
}
</span>

根據定位到的城市名獲取天氣信息實現代碼:

<span style="font-size:14px;">import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.mine.xinlangapp.R;
import com.mine.xinlangapp.activity.MainActivity;
import com.mine.xinlangapp.location.LocationUtils;
import com.mine.xinlangapp.location.TargetUrl;

public class TupianFragment extends Fragment{
	private TextView tv, tv1, tv2, tv3, tv4, tv5;
	private ImageView iv_one, iv_two;
	private static String cityName = "";
	private String result = "";
	private static Context context = null;
	private Bitmap bitmap1, bitmap2;
	private static TupianFragment tupian = null;
	public static int tupian_hour = 60;
	private static Handler handler3 = new Handler();
	@SuppressWarnings("deprecation")
	private static Runnable runnable = new Runnable() {
		@Override
		public void run() {
			tupian.getActivity().removeDialog(0);
			Toast.makeText(tupian.getActivity(), "加載失敗", Toast.LENGTH_SHORT).show();
	//		handler3.postDelayed(this, 2000);    //每兩秒執行一次runnable
		}
	};
	//自動刷新
	private Runnable runnable2 = new Runnable() {
		@Override
		public void run() {
			tupian.send(cityName);
			Message m = tupian.handler.obtainMessage();
			tupian.handler.sendMessage(m);
			handler3.postDelayed(this, tupian_hour*3600*1000);
		}
	};
	@SuppressLint("HandlerLeak")
	@SuppressWarnings("deprecation")
	public static Handler handler1 = new Handler(){
		public void handleMessage(Message msg){
			tupian.getActivity().showDialog(0);
			//啟動定時器
			handler3.postDelayed(runnable, 5000);   //五秒后執行
			new Thread(new Runnable() {
				@Override
				public void run() {
					tupian.send(cityName);
					Message m = tupian.handler.obtainMessage();
					tupian.handler.sendMessage(m);
				}
			}).start();
		}
	};
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler(){
		public void handleMessage(Message msg){
			if(result != null){
				try {
					JSONObject datajson = new JSONObject(result);  //第一步,將String格式轉換回json格式
					JSONArray results = datajson.getJSONArray("results");  //獲取results數組
					
					JSONObject city = results.getJSONObject(0);
					String currentCity = city.getString("currentCity");  //獲取city名字
					String pm25 = city.getString("pm25");   //獲取pm25
					tv.setText("城市:"+currentCity+"\n"+"pm25:"+pm25);  //測試城市和pm25
					JSONArray index = city.getJSONArray("index"); //獲取index里面的JSONArray
					//獲取穿衣
					JSONObject cy = index.getJSONObject(0);
					String titlec = cy.getString("title");
					String zsc = cy.getString("zs");
					String tiptc = cy.getString("tipt");
					String desc = cy.getString("des");
					//獲取洗車
					JSONObject xc = index.getJSONObject(1);
					String titlex = xc.getString("title");
					String zsx = xc.getString("zs");
					String tiptx = xc.getString("tipt");
					String desx = xc.getString("des");
					tv1.setText(titlec+" : "+zsc+"\n"+tiptc+" : "+desc);
					tv2.setText(titlex+" : "+zsx+"\n"+tiptx+" : "+desx);
					
					//weather_data, 未來幾天
					JSONArray weather_data = city.getJSONArray("weather_data");
					//獲取今天
					JSONObject today = weather_data.getJSONObject(0);
					String date0 = today.getString("date");
					final String dayPictureUrl0 = today.getString("dayPictureUrl");
					final String nightPictureUrl0 = today.getString("nightPictureUrl");
					String weather0 = today.getString("weather");
					String wind0 = today.getString("wind");
					String temperature0 = today.getString("temperature");	
					tv3.setText("\n"+"今天:"+date0+"\n"+"實時:"+weather0+"\n"+"風力:"+
					wind0+"\n"+"溫度范圍:"+temperature0+"\n");
					
					//獲取明天
					JSONObject tomorrow = weather_data.getJSONObject(1);
					String date1 = tomorrow.getString("date");
					String weather1 = tomorrow.getString("weather");
					String wind1 = tomorrow.getString("wind");
					String temperature1 = tomorrow.getString("temperature");
					tv4.setText("明天:"+date1+"\n"+weather1+"\n"+
					"風力:"+wind1+"\n"+"溫度范圍:"+temperature1+"\n");
					
					//獲取后天
					JSONObject after_tomorrow = weather_data.getJSONObject(2);
					String date2 = after_tomorrow.getString("date");
					String weather2 = after_tomorrow.getString("weather");
					String wind2 = after_tomorrow.getString("wind");
					String temperature2 = after_tomorrow.getString("temperature");
					tv5.setText("后天:"+date2+"\n"+weather2+"\n"+
					"風力:"+wind2+"\n"+"溫度范圍:"+temperature2+"\n");
					
					new Thread(new Runnable() {
						@Override
						public void run() {
							bitmap1 = returnBitMap(dayPictureUrl0);
							bitmap2 = returnBitMap(nightPictureUrl0);
							Message m = handler2.obtainMessage();
							handler2.sendMessage(m);
						}
					}).start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			super.handleMessage(msg);
		}
	};
	@SuppressWarnings("deprecation")
	@SuppressLint("HandlerLeak")
	private Handler handler2 = new Handler(){
		public void handleMessage(Message msg){
			if(bitmap1!=null)
				iv_one.setImageBitmap(bitmap1);
			if(bitmap2!=null)
				iv_two.setImageBitmap(bitmap2);
			if(bitmap1!=null&&bitmap2!=null){
				//停止計時器
				handler3.removeCallbacks(runnable);
				tupian.getActivity().removeDialog(0);
			}
		}
	};
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, 
			Bundle savedInstanceState){
		context = TupianFragment.this.getActivity();
		tupian = TupianFragment.this;
		LocationUtils.getCNBylocation(context);
		cityName = LocationUtils.cityName;
		MainActivity.text.setText(cityName);
		
		View view = inflater.inflate(R.layout.tupianfragment, container,false);
		iv_one = (ImageView) view.findViewById(R.id.iv_one);
		iv_two = (ImageView) view.findViewById(R.id.iv_two);
		tv = (TextView) view.findViewById(R.id.tv);
		tv1 = (TextView) view.findViewById(R.id.tv1);
		tv2 = (TextView) view.findViewById(R.id.tv2);
		tv3 = (TextView) view.findViewById(R.id.tv3);
		tv4 = (TextView) view.findViewById(R.id.tv4);
		tv5 = (TextView) view.findViewById(R.id.tv5);
		//啟動計時器
		handler3.postDelayed(runnable2, tupian_hour*3600*1000);
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				send(cityName);
				Message m = handler.obtainMessage();
				handler.sendMessage(m);
			}
		}).start();
		
		return view;
	}
	private String send(String city){
		String target = TargetUrl.url1+city+TargetUrl.url2;  //要提交的目標地址
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpRequest = new HttpGet(target);  //創建HttpGet對象
		HttpResponse httpResponse = null;
		try {
			httpResponse = httpclient.execute(httpRequest);
			if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				result = EntityUtils.toString(httpResponse.getEntity()).trim();  //獲取返回的字符串
			}else{
				result = "fail";
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	//以Bitmap的方式獲取一張圖片
	public Bitmap returnBitMap(String url){
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try{
			myFileUrl = new URL(url);
		}catch(MalformedURLException e){
			e.printStackTrace();
		}
		try{
			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		}catch(IOException e){
			e.printStackTrace();
		}
		return bitmap;
	}
	@Override
	public void onDestroy() {
		//停止計時器
		handler3.removeCallbacks(runnable2);
		super.onDestroy();
	}
}
</span>

最后別忘記添加權限:

<span style="font-size:14px;">    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /></span>


說明:

<span style="font-size:14px;">criteria.setAccuracy(Criteria.ACCURACY_LOW);    //低精度   高精度:ACCURACY_FINE 
使用網絡定位要選擇低精度,如果選擇了高精度它會第一選擇為:GPS定位,沒有開啟GPS定位,才會使用網絡定位。
</span>

關注公眾號,分享干貨,討論技術



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM