先看效果:
需求非常简单,在菜单中加入天气查询的按钮,点击后显示即时天气。
准备工作:
1.下载华为能力SDK;http://imax.vmall.com/nj-campus/universityEpDown/toDownPage
2.申请一个应用获取appId和appkey,待会要用到。
简单的思路就是先通过网络或者gps获取到当前位置的经纬度,然后通过sdk查询温度,获取结果。
具体步骤如下:
1.创建工程
把sdk中jar包拖到工程中的libs文件夹下面。
2.主类代码如下
package com.empty.weatherreport; import com.empty.weatherreport.WeatherUtil.SCell; import com.empty.weatherreport.WeatherUtil.SItude; import com.imax.vmall.sdk.android.common.adapter.ServiceCallback; import com.imax.vmall.sdk.android.entry.CapabilityService; import com.imax.vmall.sdk.android.entry.CommonService; import com.imax.vmall.sdk.android.huawei.weather.WeatherService; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; public class WeatherActivity extends Activity { private MyHandler myHandler; private ProgressDialog mProgressDialog; private Location mLocation; private boolean sdkStatus; //Tool to get weather /** * CommonService */ private CommonService cs; /** * WeatherService */ private WeatherService weather; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_weather); sdkStatus=false; myHandler=new MyHandler(); //初始化业务接口实例 weather = CapabilityService.getWeatherServiceInstance(); //实例化CommonService cs=CommonService.getInstance(); initSDK(); } private void initSDK() { //应用ID,请去iMAX平台注册申请 String appId="******"; //应用Key String appKey="******"; //通过CommonService调用鉴权接口,在调用其它能力前必须保证鉴权初始化成功 cs.init(WeatherActivity.this,appId, appKey, new ServiceCallback() { public void onError(String arg0) { // TODO Auto-generated method stub //设置消息 Message msg = new Message(); msg = new Message(); msg.what = 2; msg.obj = "SDK initialize failed!"; myHandler.sendMessage(msg); } public void onComplete(String arg0) { // TODO Auto-generated method stub //设置消息 Message msg = new Message(); msg = new Message(); msg.what = 2; msg.obj = "SDK initialize success!"; sdkStatus=true; myHandler.sendMessage(msg); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_weather, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { // TODO Auto-generated method stub if(item.getItemId()==R.id.menu_settings) Toast.makeText(getApplicationContext(), "Ha", Toast.LENGTH_SHORT).show(); if(item.getItemId()==R.id.menu_weather) { if(sdkStatus) { /** 弹出一个等待状态的框 */ mProgressDialog = new ProgressDialog(this); mProgressDialog.setMessage("Waiting..."); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.show(); WeatherThread m = new WeatherThread(); new Thread(m).start(); } else Toast.makeText(getApplicationContext(), "SDK not installed", Toast.LENGTH_SHORT).show(); } return super.onMenuItemSelected(featureId, item); } /** 显示结果 */ private void showResult(String s) { String tmp[]=s.split("\""); for(int i=0;i<tmp.length;i++) Log.i("tmp"+i, tmp[i]); new AlertDialog.Builder(this) .setTitle("Weather") .setMessage("latitude:"+mLocation.getLatitude()+"\n longitude:" +mLocation.getLongitude()+"\ntmperature:"+tmp[21]) .show(); } class MyHandler extends Handler { public MyHandler() { } public MyHandler(Looper L) { super(L); } // 子类必须重写此方法,接管数据 @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub Log.d("MyHandler", "handleMessage......"); /** 显示结果 */ switch(msg.what) { case 1: Log.i("Error", "case1"); mProgressDialog.dismiss(); showResult((String)msg.obj); break; case 2: Toast.makeText(getApplicationContext(), (String)msg.obj, Toast.LENGTH_SHORT).show(); break; default:; } super.handleMessage(msg); // 此处可以更新UI } } class WeatherThread implements Runnable { public void run() { final Message msg = new Message(); msg.what=1; try { mLocation=getLocation(WeatherActivity.this); weather.getWeather(Double.toString(mLocation.getLongitude()),Double.toString(mLocation.getLatitude()), new ServiceCallback() { public void onError(String arg0) { //api接口调用错误响应 Log.i("Error", "getWeather error:"+arg0); //设置消息 msg.obj = arg0; /** 关闭对话框 */ myHandler.sendMessage(msg); // 向Handler发送消息,更新UI } public void onComplete(String arg0) { //api接口调用成功响应 Log.i("Complete", "getWeather complete:"+arg0); //设置消息 msg.obj = arg0; /** 关闭对话框 */ myHandler.sendMessage(msg); // 向Handler发送消息,更新UI } }); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //Get the Location by GPS or WIFI public Location getLocation(Context context) { LocationManager locMan = (LocationManager) context .getSystemService(Context.LOCATION_SERVICE); Location location = locMan .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) { location = locMan .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } return location; } }
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" > </uses-permission> <uses-permission android:name="android.permission.INTERNET" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" />
增强版
光用文字表现力还是不够,下面来实现图片显示天气情况。
思路就是根据返回的结果字段,更新imageview。
首先在res/drwable中添加一些表示天气的图片:
在主界面中添加一个ImageView空间。
修改 private void showResult(String s)函数。
/** 显示结果 */ private void showResult(String s) { String tmp[]=s.split("\""); for(int i=0;i<tmp.length;i++) Log.i("tmp"+i, tmp[i]); new AlertDialog.Builder(this) .setTitle("Weather") .setMessage("latitude:"+mLocation.getLatitude()+"\n longitude:" +mLocation.getLongitude()+"\ntmperature:"+tmp[21]+s).show(); int weatherCode = Integer.parseInt(tmp[13]); switch(weatherCode){ case 26: case 27: case 28: case 29: case 30: case 44: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.cloudy)); break; case 20: case 22: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.foggy)); break; case 21: case 19: case 23: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.dusty)); break; case 24: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.windy)); break; case 36: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.hot)); break; case 13: case 14: case 15: case 16: case 43: case 46: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.snow)); break; case 3: case 4: case 37: case 38: case 39: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.thunderstorms)); break; case 11: case 12: case 40: case 45: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.showers)); break; case 5: case 6: case 7: case 18: case 35: case 41: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.mixrainandsnow)); break; case 32: case 34: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.sunny)); break; case 8: case 9: case 10: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.freezerain)); break; case 17: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.hail)); break; case 1: case 2: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.tornado)); break; case 25: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.cold)); break; case 31: case 33: mImageView.setImageDrawable(this.getResources().getDrawable(R.drawable.clear)); break; default:; } }