实战开发-Ashurol天气预报APP(四)

来源:互联网 发布:华新数控螺紋编程 编辑:程序博客网 时间:2024/06/05 23:54

  趁热打铁,现在进入第四阶段的代码编写。在上一阶段结束后会存在一个问题,当你选择一个城市后,就没有办法查看其它城市的天气了,及时退出,下一次进来后还会直接跳转到WeatherActivity.这里就将代码优化一下

在weather_layout中加入两个按钮,前一阶段已经提前加入了,这里就不重复给代码了

接着修改WeatherActivity活动里的代码

定义按钮,注册监听器,实现监听方法

/* *切换城市按钮 */private Button switchCity;/* *更换天气按钮 */private Button refreshWeather;                switchCity=(Button) findViewById(R.id.switch_city);refreshWeather=(Button) findViewById(R.id.refresh_weather);switchCity.setOnClickListener(this);refreshWeather.setOnClickListener(this);
/* * 判断当前操作 */@Overridepublic void onClick(View v) {// TODO Auto-generated method stubswitch(v.getId()){case R.id.switch_city:Intent intent=new Intent(this,ChooseAreaActivity.class);intent.putExtra("from_weather_activity", true);startActivity(intent);finish();break;case R.id.refresh_weather:publishText.setText("同步中...");SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);String weatherCode=prefs.getString("weather_code", "");if(!TextUtils.isEmpty(weatherCode)){queryWeatherInfo(weatherCode);}break;default:break;}}

当点击的是切换城市按钮,由于目前已经选过一个城市,如果直接跳转到ChooseAreaActivity,会立刻又跳回来,因此这里要在Intent中加入一个from_weather_activity标志位

,接着更改ChooseAreaActivity对这个标志位进行处理,定义一个Boolean值

/*
* 是否从WeatherActivity中跳转过来
*/
private boolean isFromWeatherActivity;
接着在Oncreate()方法中添加一下代码

isFromWeatherActivity=getIntent().getBooleanExtra("from_weather_activity", false);

//已经选择了城市且不是从WeatherActivity跳转过来,才会直接跳转到WeatherActivityif(prefs.getBoolean("city_selected", false)<strong>&&!isFromWeatherActivity</strong>){Intent intent=new Intent(this,WeatherActivity.class);startActivity(intent);finish();return;}

另外在OnbackPressed()中加入if()判断,当按下Back键时,如果是从WeatherActivity跳转过来的,则应该重新回到WeatherActivity。代码如下

public void onBackPressed(){if(currentLevel==LEVEL_COUNTY){queryCities();}else if(currentLevel==LEVEL_CITY){queryProvinces();}else{if(isFromWeatherActivity){Intent intent=new Intent(this,WeatherActivity.class);startActivity(intent);}finish();}}

现在切换城市的按钮以及更新天气的按钮功能已经完成了。

最后添加APP的最后一个功能

为了让程序更加智能,这里考虑加入自动更新天气的功能。首先在service包中新建一个AutoUpdateService继承Service,代码如下:

public class AutoUpdateService extends Service{@Overridepublic IBinder onBind(Intent arg0) {// TODO Auto-generated method stubreturn null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// TODO Auto-generated method stubnew Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubupdateWeather();}}).start();AlarmManager manager=(AlarmManager) getSystemService(ALARM_SERVICE);int anHour=8*60*60*1000;//这时8小时的毫秒数long triggerAtTime=SystemClock.elapsedRealtime()+anHour;Intent i=new Intent(this,AutoUpdateReceiver.class);PendingIntent pi=PendingIntent.getBroadcast(this, 0, i, 0);manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);return super.onStartCommand(intent, flags, startId);}private void updateWeather(){SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);String weatherCode=prefs.getString("weather_code", "");String address="http://www.weather.com.cn/data/cityinfo/"+weatherCode+".html";HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {@Overridepublic void onFinish(String response) {// TODO Auto-generated method stubUtility.handleWeatherResponse(AutoUpdateService.this, response);}@Overridepublic void onError(Exception e) {// TODO Auto-generated method stub}});}}

在onstartCommand()方法中先开启一个子线程,然后在子线程中调用updateWeather()方法来更新天气。还需要创建BroadcastReceive,来辅助实现定时刷新功能,代码如下:

public class AutoUpdateReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubIntent i=new Intent(context,AutoUpdateService.class);context.startService(i);}}

通过OnReceive()中再次启动AutoUpdateService,就可以实现后台定时

最后需要在代码某处去第一次启动AutoUpdateService,在WeatherActivity中的showWeather()中最后加入

//激活AutoUpdateServiceIntent intent=new Intent(this,AutoUpdateService.class);startService(intent);

最后别忘了在AndroidManifest中注册新增的服务于广播

        <service             android:name="service.AutoUpdateService">                    </service>        <receiver android:name="receiver.AutoUpdateReceiver">                    </receiver>
一个好的App图标可以增彩不少,现在我们就为程序添加一个性感的图标

在AndroidManifest.xml文件中里的icon属性更改默认的Android图标

 <application        android:allowBackup="true"        android:icon="@drawable/logo"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="activity.ChooseAreaActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity            android:name="activity.WeatherActivity"            android:label="@string/app_name" >                    </activity>        <service             android:name="service.AutoUpdateService">                    </service>        <receiver android:name="receiver.AutoUpdateReceiver">                    </receiver>            </application>

最后在res/values/string.xml中更改下应用名称

<resources>    <string name="app_name">Ashurol天气</string>    <string name="hello_world">Hello world!</string>    <string name="action_settings">Settings</string></resources>
到这里,App也按初定实现目标完成了!

最后在叨逼一句,

---梦想还是要有的,万一不小心实现了呢!

花万分的努力,乘以1/10000,等于百分之百的实现!今天你我努力了吗?



0 0
原创粉丝点击