利用Handler更简单的实现Service与Activity的通信,更新UI

Service与Activity通信主要有两种方法:

1)利用广播Broadcas,特点:消耗大,但是可以通知多个activity。

2)利用Handler快速实现Service和activity的通信。

3)还有前边介绍的接口回掉+Handler。

在这里介绍第二种方法,也就是最简单的方法:

布局文件:

<pre name="code" class="java"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
        />
      <Button 
          android:id="@+id/bindService_btn"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:text="启动service"
          />
        <TextView
            android:id="@+id/ceshiText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
      <Button android:id="@+id/unbindButton" 
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:text="解绑Service"
        />
</LinearLayout>

 
//Service类,模仿下载线程
</pre><pre name="code" class="java">public class DownService extends Service {

	private int i=0;
	private boolean isStop;
	public DownService() {
		System.out.println("实例化downService");
	}
   
	public void onCreate() {
        
		System.out.println("downService->onCreate");
		new Thread(new DownThread()).start();//启动线程
		super.onCreate();
	}
    
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		return super.onStartCommand(intent, flags, startId);
	}

	public void onDestroy() {
		super.onDestroy();
		isStop=true;
		System.out.println("downService->onDestroy");
	}
	//每个一秒发一个通知
    class DownThread implements Runnable{
         
		public void run() {
			while(!isStop){
				i++;
            try {
				Thread.sleep(1000);
				 Message msg = new Message(); 
	              msg.what = i;
				MainActivity.handler.sendMessage(msg); 
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	 }
   }
    
    public boolean isStop() {
		return isStop;
	}
	public void setStop(boolean isStop) {
		this.isStop = isStop;
	}

	public IBinder onBind(Intent intent) {
        System.out.println("onBind");
        
		return echoBinder;
	}
   private CountBinder echoBinder = new CountBinder();
	
    public class CountBinder extends Binder{
    	public DownService getService(){
    		return DownService.this;
    	}
    }
 
}

Activity与Service交互,更新UI。
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

	Button bindButton,unbindButton;
	TextView ceshiTextView;
	public static MyHandler handler; 
	Intent intent;
	int i=0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		initEvent();
	}
	
	private void initView() {
		handler = new MyHandler();
		bindButton = (Button) findViewById(R.id.bindService_btn);//注册观察者
		unbindButton = (Button) findViewById(R.id.unbindButton);//删除观察者
		ceshiTextView = (TextView) findViewById(R.id.ceshiText);   
        		
	}
	private void initEvent() {
		bindButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				intent = new Intent(MainActivity.this, DownService.class);  //描述跳转服务的intent
				startService(intent);
			}
		});
		unbindButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				stopService(intent);
			}
		});
	}
	class MyHandler extends Handler{

		@Override
		public void handleMessage(Message msg) {
			if(msg.what!=0){
				int i = msg.what;
				ceshiTextView.setText("下载了:"+i);
			}
			
		}
		
	}
}
代码很简单,相信一看就明白。。。

转载请注明出处:http://blog.csdn.net/jycboy

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值