Service和廣播聯合更新UI的例子

來源:互聯網
上載者:User

標籤:android   des   http   資料   os   art   

sa111111 於 2010-11-19 10:56 發表在 [Android執行個體] [複製連結] [只看樓主] [上一主題] [下一主題]  

在Android中,非同步更新UI,通常我們會選用Handler啟動線程,或者sendMessage的方式,那麼利用Service和廣播也可以更新UI的,例子如下:
我們建立一個Service:
package com.andy
import android.app.Service;//引入相關包
import android.content.BroadcastReceiver;//引入相關包
import android.content.Context;//引入相關包
import android.content.Intent;//引入相關包
import android.content.IntentFilter;//引入相關包
import android.os.IBinder;//引入相關包
//繼承自Service的子類
public class MyService extends Service{
        CommandReceiver cmdReceiver;
        boolean flag;
        @Override
        public void onCreate() {//重寫onCreate方法
                flag = true;
                cmdReceiver = new CommandReceiver();
                super.onCreate();
        }
        @Override
        public IBinder onBind(Intent intent) {//重寫onBind方法
                // TODO Auto-generated method stub
                return null;
        }
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {//重寫onStartCommand方法
                IntentFilter filter = new IntentFilter();//建立IntentFilter對象
                filter.addAction("wyf.wpf.MyService");
                registerReceiver(cmdReceiver, filter);//註冊Broadcast Receiver
                doJob();//調用方法啟動線程
                return super.onStartCommand(intent, flags, startId);
        }
        //方法:
        public void doJob(){
                new Thread(){
                        public void run(){
                                while(flag){
                                        try{//睡眠一段時間
                                                Thread.sleep(1000);
                                        }
                                        catch(Exception e){
                                                e.printStackTrace();
                                        }
                                        Intent intent = new Intent();//建立Intent對象
                                        intent.setAction("wyf.wpf.Sample_3_6");
                                        intent.putExtra("data", Math.random());
                                        sendBroadcast(intent);//發送廣播
                                }                               
                        }
                       
                }.start();
        }       
        private class CommandReceiver extends BroadcastReceiver{//繼承自BroadcastReceiver的子類
                @Override
                public void onReceive(Context context, Intent intent) {//重寫onReceive方法
                        int cmd = intent.getIntExtra("cmd", -1);//擷取Extra資訊
                        if(cmd == Sample_3_6.CMD_STOP_SERVICE){//如果發來的訊息是停止服務                               
                                flag = false;//停止線程
                                stopSelf();//停止服務
                        }
                }               
        }
        @Override
        public void onDestroy() {//重寫onDestroy方法
                this.unregisterReceiver(cmdReceiver);//取消註冊的CommandReceiver
                super.onDestroy();
        }       
}

建立一個activity

package com.andy;//聲明包語句
import android.app.Activity;//引入相關包
import android.content.BroadcastReceiver;//引入相關包
import android.content.Context;//引入相關包
import android.content.Intent;//引入相關包
import android.content.IntentFilter;//引入相關包
import android.os.Bundle;//引入相關包
import android.view.View;//引入相關包
import android.view.View.OnClickListener;//引入相關包
import android.widget.Button;//引入相關包
import android.widget.TextView;//引入相關包
//繼承自Activity的子類
public class Sample_3_6 extends Activity {
        public static final int CMD_STOP_SERVICE = 0;
        Button btnStart;//開始服務Button對象應用
        Button btnStop;//停止服務Button對象應用
        TextView tv;//TextView對象應用
        DataReceiver dataReceiver;//BroadcastReceiver對象
        @Override
    public void onCreate(Bundle savedInstanceState) {//重寫onCreate方法
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);//設定顯示的螢幕
        btnStart = (Button)findViewById(R.id.btnStart);
        btnStop = (Button)findViewById(R.id.btnStop);
        tv = (TextView)findViewById(R.id.tv);
        btnStart.setOnClickListener(new OnClickListener() {//為按鈕添加點擊事件監聽               
                        @Override
                        public void onClick(View v) {//重寫onClick方法
                                Intent myIntent = new Intent(Sample_3_6.this, wyf.wpf.MyService.class);
                                Sample_3_6.this.startService(myIntent);//發送Intent啟動Service
                        }
                });
        btnStop.setOnClickListener(new OnClickListener() {//為按鈕添加點擊事件監聽       
                        @Override
                        public void onClick(View v) {//重寫onClick方法
                                Intent myIntent = new Intent();//建立Intent對象
                                myIntent.setAction("wyf.wpf.MyService");
                                myIntent.putExtra("cmd", CMD_STOP_SERVICE);
                                sendBroadcast(myIntent);//發送廣播
                        }
                });
    }       
        private class DataReceiver extends BroadcastReceiver{//繼承自BroadcastReceiver的子類
                @Override
                public void onReceive(Context context, Intent intent) {//重寫onReceive方法
                        double data = intent.getDoubleExtra("data", 0);
                        tv.setText("Service的資料為:"+data);                       
                }               
        }
        @Override
        protected void onStart() {//重寫onStart方法
                dataReceiver = new DataReceiver();
                IntentFilter filter = new IntentFilter();//建立IntentFilter對象
                filter.addAction("wyf.wpf.Sample_3_6");
                registerReceiver(dataReceiver, filter);//註冊Broadcast Receiver
                super.onStart();
        }
        @Override
        protected void onStop() {//重寫onStop方法
                unregisterReceiver(dataReceiver);//取消註冊Broadcast Receiver
                super.onStop();
        }

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.