接口回调实现 View和Data分离。

xiaoxiao2021-02-28  21

集成高德SDK,获取定位和天气 Demo

View 和Data逻辑分离

数据获取到后,通过回调接口传递数据

接口文件 ,为了传递数据到Activity

public interface CallBack { /** * 获得定位地点 */ public void getCity(String city); /** * 获取天气数据 */ public void getWeatherData(String weather,String temper,String weatherCity); }

数据获取逻辑

import java.text.SimpleDateFormat; import java.util.Date; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationListener; import com.amap.api.location.AMapLocationClientOption.AMapLocationMode; import com.amap.api.services.weather.LocalWeatherForecastResult; import com.amap.api.services.weather.LocalWeatherLive; import com.amap.api.services.weather.LocalWeatherLiveResult; import com.amap.api.services.weather.WeatherSearch; import com.amap.api.services.weather.WeatherSearchQuery; import com.amap.api.services.weather.WeatherSearch.OnWeatherSearchListener; public class Weather implements OnWeatherSearchListener, AMapLocationListener { public String TAG = this.getClass().getName(); public static final String CONNECTIVITY_SERVICE = "connectivity"; // 定位 public AMapLocationClient mlocationClient; // 声明mLocationOption对象 public AMapLocationClientOption mLocationOption = null; private String City; // weather private WeatherSearchQuery mquery; private WeatherSearch mweathersearch; private String WeatherBackCity; // 定时线程 private Thread mWeatherThread = null; private int WETHER_REQUEST_SLEEP_SWITCH = 0; // 回调接口 CallBack mWeatherCallBack; public void setCallBack(CallBack mWeatherCallBack) { this.mWeatherCallBack = mWeatherCallBack; } public void initData(Context mContext){ boolean isanailiable = isAvailiableTheNetWork(mContext); if (isanailiable) { initLocation(mContext); setTimeGetWeather(); InitWeather(City); Log.e(TAG, "onCreate initLocation"); } } /** * * @Title: isAvailiableTheNetWork * @Description: TODO(检查网络是否可用) * @param context * @return boolean true 可用 ;false 不可用 */ public boolean isAvailiableTheNetWork(Context context) { ConnectivityManager manage = (ConnectivityManager) context.getApplicationContext().getSystemService(CONNECTIVITY_SERVICE); if (manage == null) { return false; } NetworkInfo networkInfo = manage.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isAvailable()) { return false; } return true; } /** * 初始化定位 */ public void initLocation(Context mContext) { if(mlocationClient != null && mLocationOption !=null ){ return; } mlocationClient = new AMapLocationClient(mContext); // 初始化定位参数 mLocationOption = new AMapLocationClientOption(); // 设置定位监听 mlocationClient.setLocationListener(this); // 设置定位模式为高精度模式,Battery_Saving为低功耗模式,Device_Sensors是仅设备模式 mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy); // 设置定位间隔,单位毫秒,默认为2000ms mLocationOption.setInterval(1 * 60 * 1000); // 半个小时获取一次定位 // mLocationOption.setOnceLocation(true); // 设置定位参数 // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗, // 注意设置合适的定位时间的间隔(最小间隔支持为1000ms),并且在合适时间调用stopLocation()方法来取消定位请求 // 在定位结束后,在合适的生命周期调用onDestroy()方法 // 在单次定位情况下,定位无论成功与否,都无需调用stopLocation()方法移除请求,定位sdk内部会移除 // 启动定位 mlocationClient.setLocationOption(mLocationOption); mlocationClient.startLocation(); } /** * 定位回调 */ @Override public void onLocationChanged(AMapLocation amapLocation) { // TODO Auto-generated method stub if (amapLocation != null) { if (amapLocation.getErrorCode() == 0) { // 定位成功回调信息,设置相关消息 amapLocation.getLocationType();// 获取当前定位结果来源,如网络定位结果,详见定位类型表 amapLocation.getAccuracy();// 获取精度信息 City = amapLocation.getCity(); Log.e(TAG, "[定位城市]=" + amapLocation.getCity()); // 回调 mWeatherCallBack.getCity(amapLocation.getCity()); // 获取时间 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(amapLocation.getTime()); df.format(date);// 定位时间 } else { // 显示错误信息ErrCode是错误码,errInfo是错误信息,详见错误码表。 Log.e(TAG, "location Error, ErrCode:" + amapLocation.getErrorCode() + ", errInfo:" + amapLocation.getErrorInfo()); } if (City == null) { } else { if (City != WeatherBackCity) { InitWeather(City); } } } } /** * 停止定位 */ public void stopLocation() { if (mlocationClient != null) { mlocationClient.onDestroy(); mlocationClient.stopLocation(); mlocationClient = null; mLocationOption = null; Log.e(TAG, "[mlocationClient is null]"); } Log.e(TAG, "stop location"); } /** * * @Title: getWeather * @Description: 初始化天气 * @return void 返回类型 * @throws */ public void InitWeather(String city) { if (city != null) { mquery = new WeatherSearchQuery(city, WeatherSearchQuery.WEATHER_TYPE_LIVE); mweathersearch = new WeatherSearch(MainActivity.mContext); mweathersearch.setOnWeatherSearchListener(this); mweathersearch.setQuery(mquery); mweathersearch.searchWeatherAsyn(); // 异步搜索 } else { Log.e(TAG, "[initWeather the city is null]"); } } /** * 天气回调 */ @Override public void onWeatherForecastSearched(LocalWeatherForecastResult arg0, int arg1) { // TODO Auto-generated method stub } @Override public void onWeatherLiveSearched(LocalWeatherLiveResult weatherLiveResult, int rCode) { // TODO Auto-generated method stub if (rCode == 1000) { if (weatherLiveResult != null && weatherLiveResult.getLiveResult() != null) { LocalWeatherLive liveResult = weatherLiveResult.getLiveResult(); String time = liveResult.getReportTime(); String weather = liveResult.getWeather(); String temper = liveResult.getTemperature(); WeatherBackCity = liveResult.getCity(); mWeatherCallBack.getWeatherData(weather, temper, WeatherBackCity); Log.e(TAG, "[时间]" + time + "[天气]=" + weather + "[温度]=" + temper + "[城市]=" + WeatherBackCity); // tv_show.setText("[时间]" + time + "[天气]=" + weather + "[温度]=" + temper + "[城市]=" + WeatherBackCity); } else { Log.e(TAG, "[weatherLiveResult is null]"); } } else { Log.e(TAG, "[rCode is erro]=" + rCode); } } /** * 定时获取天气 */ public void setTimeGetWeather() { // 检索参数为城市和天气类型,实况天气为WEATHER_TYPE_LIVE、天气预报为WEATHER_TYPE_FORECAST if (null != mWeatherThread) { Log.e(TAG, "init_wether() mWeatherThread!=null, so return!!!"); return; } mWeatherThread = new Thread(new Runnable() { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { // get data if (WeatherBackCity == null) { WETHER_REQUEST_SLEEP_SWITCH = 0; } else { WETHER_REQUEST_SLEEP_SWITCH = 1; } try { Log.e(TAG, "WETHER_REQUEST_SLEEP_SWITCH :" + WETHER_REQUEST_SLEEP_SWITCH); if (WETHER_REQUEST_SLEEP_SWITCH == 0) { Log.e(TAG, "sleep = 15 s"); Thread.sleep(15 * 1000); } else { Log.e(TAG, "sleep = 2 h"); Thread.sleep(2 * 60 * 1000);// three hours update once } InitWeather(City); } catch (Exception e) { e.printStackTrace(); Thread.currentThread().interrupt(); mWeatherThread = null; } } } // TODO Auto-generated method stub }); mWeatherThread.start(); } /** * 停止天气获取线程 * */ private void stop_wether() { Log.d(TAG, "stop_wether() enter"); try { if (mWeatherThread != null) { mWeatherThread.interrupt(); mWeatherThread = null; } } catch (Exception e) { e.printStackTrace(); } } /** * * @Title: onDestory */ public void onDestory() { stopLocation(); stop_wether(); } }

view 显示

package com.tricheer.weatherdemo; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; public class MainActivity extends Activity implements OnClickListener, CallBack { private String TAG = "ybfwe"; private Button mbt; private EditText med_text; private TextView tv_show; // 显示天气 private TextView tv_showLocation; // 显示定位城市 Weather mewWeather; // 定位 public AMapLocationClient mlocationClient; // 声明mLocationOption对象 public AMapLocationClientOption mLocationOption = null; BroadcastReceiver networkChangeReceiver; public static Context mContext; public String mWeatherCity = null; // 1.请求天气 需求 // 2.定位半个小时一次,天气两个小时获取一次。 // 3. 定位设置30分钟一次,设置间隔时间。或者通过定时获取定位。 // 4. 半个小时获取到地里位置不同,请求一次天气。 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mContext = getApplicationContext(); initCallback(); initView(); initBroadcast(); } private void initCallback() { // TODO Auto-generated method stub mewWeather = new Weather(); mewWeather.initLocation(mContext); mewWeather.setCallBack(this); mewWeather.initData(mContext); } private void initView() { mbt = (Button) findViewById(R.id.bt); mbt.setOnClickListener(this); med_text = (EditText) findViewById(R.id.ed_text); tv_show = (TextView) findViewById(R.id.tv_show); tv_showLocation = (TextView) findViewById(R.id.tv_showLocation); } private void initBroadcast() { // TODO Auto-generated method stub IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); // 广播接收器想要监听什么广播,就在这里添加相应的action networkChangeReceiver = new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver, intentFilter); // registerReceiver(networkChangeReceiver,intentFilter); //调用resigerReceiver()方法进行 } class NetworkChangeReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show(); ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // 得到系统服务类 NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isAvailable()) { boolean isanailiable = mewWeather.isAvailiableTheNetWork(context); if (isanailiable) { mewWeather.initData(context); } Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show(); } } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); /* unregisterReceiver(networkChangeReceiver); */ mewWeather.onDestory(); } @Override public void onClick(View v) { // TODO Auto-generated method stub String city = med_text.getText().toString(); if (city == null) { return; } Log.e(TAG, "onclick city = " + city); } @Override public void getCity(String city) { Log.e("callback", "LocationCity = " + city); } @Override public void getWeatherData(String weather, String temper, String weatherCity) { // TODO Auto-generated method stub mWeatherCity = weatherCity; Log.e(TAG, "getCity = " + "[weather]" + weather + "[temper]" + temper + "[weatherCity]" + weatherCity); tv_show.setText(weather + "-" + temper); tv_showLocation.setText(weatherCity); } }
转载请注明原文地址: https://www.6miu.com/read-1600138.html

最新回复(0)