简述:
Android 开发过程中,Service 作为重要的组件,起到了后台运行数据(包括请求、运算、响应等)功能,所以有必要写一个初级的模型来加深一下认识
设计:
想了一个简单的实现, 在主页面点击Run按钮,开始输出数字,使用定时器在Service定时更新当前页面的TextView, 点击Stop则停止这一更改。同时涉及到Handler的内存泄露问题的弱引用解决法
代码:
1. 项目结构
2. 基本配置和UI
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.anialy.testproj"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".part1.activity.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".part1.service.MainService"
android:enabled="true"
android:exported="false" >
</service>
</application>
</manifest>
dimen.xml
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>
String.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TestProj</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
</resources>
主页
MainActivity.java
package com.anialy.testproj.part1.activity;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.anialy.testproj.R;
import com.anialy.testproj.part1.service.MainService;
import com.anialy.testproj.part1.service.MainService.ServiceBinder;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
/**
* service 定义实现绑定部分
*/
private MainService mService;
private Intent intentService;
private CustomizedEvent cusEvent;
private boolean isStart = false;
/**
* service连接监听
*/
private ServiceConnection serviceCon = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
if (mService == null) {
mService = ((ServiceBinder) service).getService();
}
// 在service中诸如修改UI的实现cusEvent
mService.setCusEvent(cusEvent);
}
};
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause !");
unbindService(serviceCon);
}
@Override
protected void onResume() {
Log.i(TAG, "onResume !");
super.onResume();
}
//////////////////////////////////////////////////////////////////////////////
/**
* 定义控件
*/
private Button btn;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate !");
setContentView(R.layout.activity_main);
initWidgets();
initEvents();
}
private void initWidgets(){
btn = (Button) findViewById(R.id.btn);
tv = (TextView) findViewById(R.id.tv);
}
protected void initEvents(){
// 定义修改UI的参数, 可以以接口实现的形式传到service, 在service中修改当前UI
cusEvent = new CustomizedEvent() {
private static final long serialVersionUID = -3269070363866254175L;
@Override
public void doSomething(int cnt) {
tv.setText(tv.getText() + String.valueOf(cnt) + ", ");
}
};
// 点击之后启动service
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
intentService = new Intent(MainActivity.this, MainService.class);
startService(intentService);
if( !isStart ){
bindService(intentService, serviceCon, Context.BIND_AUTO_CREATE);
if(mService != null)
mService.startTimer();
btn.setText("Stop");
}else{
mService.stopTimer();
btn.setText("Run");
}
isStart = !isStart;
}
});
}
}
主页配置文件activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="Run" />
<TextView
android:id="@+id/tv"
android:layout_width="400dip"
android:layout_height="300dip"
android:layout_below="@+id/btn"
android:layout_centerHorizontal="true"
android:layout_marginLeft="24dp"
android:layout_marginTop="20dp" />
</RelativeLayout>
3. 主页界面更改的接口
CustomizeEvent.java
package com.anialy.testproj.part1.activity;
import java.io.Serializable;
public interface CustomizedEvent extends Serializable {
public void doSomething(int cnt);
}
4. service实现定时更新
package com.anialy.testproj.part1.service;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import com.anialy.testproj.part1.activity.CustomizedEvent;
public class MainService extends Service {
private static final String TAG = "MainService";
private CustomizedEvent cusEvent; //定义接口,用来传递MainActivity传来的函数
private ServiceBinder serviceBinder = new ServiceBinder();
public void setCusEvent(CustomizedEvent cusEvent) {
this.cusEvent = cusEvent;
}
public MainService() {
}
/**
* 自定义binder类 返回当前的 service
*
* @author Administrator
*
*/
public class ServiceBinder extends Binder {
public MainService getService() {
return MainService.this;
}
}
Timer timer = new Timer();
TimerTask task;
private static int cnt = 0;
private static final int CHANGE_OK = 0x1;
// 解决handler内存泄露
private MyHandler handler = new MyHandler(this);
private static class MyHandler extends Handler {
WeakReference<MainService> mService;
MyHandler(MainService mService){
this.mService = new WeakReference<MainService>(mService);
}
public void handleMessage(Message msg) {
switch(msg.what){
case CHANGE_OK :
mService.get().cusEvent.doSomething(++cnt);
}
};
};
// 开始定时发送
public void startTimer() {
task = new TimerTask(){
@Override
public void run() {
Log.i(TAG, "timer begins !!!");
handler.sendEmptyMessage(CHANGE_OK);
}
};
timer.schedule(task, 1000, 1000);
}
// 结束定时发送
public void stopTimer(){
task.cancel();
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, " onCreate !");
startTimer();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, " onStart !");
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, " onBind !");
return serviceBinder;
}
@Override
public boolean onUnbind(Intent intent) {
timer.cancel();
return super.onUnbind(intent);
}
@Override
public void onDestroy() {
Log.i(TAG, " onDestroy !");
super.onDestroy();
}
}
界面展示: 未开始前Run等待状态
点击Run开始service, 按钮变为Stop
点击Stop结束,按钮从Stop变为Run