Activity與Service通信

參考文章:
http://www.runoob.com/w3cnote/android-tutorial-service-2.html
http://blog.csdn.net/xiaanming/article/details/9750689

假如我們啓動的是一個下載 的後臺Service,而我們想知道Service中下載任務的進度!那麼這肯定是需要Service 與Activity進行通信的,可以通過兩種方式進行通信,Binder對象和broadcast。

1.通過Binder對象

基本步驟:
1. 自定義Service中,定義一個Binder類,然後將需要暴露的方法都寫到該類中!
2. Service類中,實例化這個自定義Binder類,然後重寫onBind()方法,將這個Binder對象返回!
3. Activity類中實例化一個ServiceConnection對象,重寫onServiceConnected()方法,然後 獲取Binder對象,然後調用相關方法即可!

示例代碼:

http://blog.csdn.net/kinglong68/article/details/51013022 中的”2.BindService”

2.通過broadcast(廣播)的形式

當我們的進度發生變化的時候我們發送一條廣播,然後在Activity的註冊廣播接收器,接收到廣播之後更新ProgressBar,代碼如下

public class MainActivity extends Activity {  
    private ProgressBar mProgressBar;  
    private Intent mIntent;  
    private MsgReceiver msgReceiver;  


    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  

        //動態註冊廣播接收器  
        msgReceiver = new MsgReceiver();  
        IntentFilter intentFilter = new IntentFilter();  
        intentFilter.addAction("com.example.communication.RECEIVER");  
        registerReceiver(msgReceiver, intentFilter);  


        mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);  
        Button mButton = (Button) findViewById(R.id.button1);  
        mButton.setOnClickListener(new OnClickListener() {  

            @Override  
            public void onClick(View v) {  
                //啓動服務  
                mIntent = new Intent("com.example.communication.MSG_ACTION");  
                startService(mIntent);  
            }  
        });  

    }  


    @Override  
    protected void onDestroy() {  
        //停止服務  
        stopService(mIntent);  
        //註銷廣播  
        unregisterReceiver(msgReceiver);  
        super.onDestroy();  
    }  


    /** 
     * 廣播接收器 
     * @author len 
     * 
     */  
    public class MsgReceiver extends BroadcastReceiver{  

        @Override  
        public void onReceive(Context context, Intent intent) {  
            //拿到進度,更新UI  
            int progress = intent.getIntExtra("progress", 0);  
            mProgressBar.setProgress(progress);  
        }  

    }  

}  
public class MsgService extends Service {  
    /** 
     * 進度條的最大值 
     */  
    public static final int MAX_PROGRESS = 100;  
    /** 
     * 進度條的進度值 
     */  
    private int progress = 0;  

    private Intent intent = new Intent("com.example.communication.RECEIVER");  


    /** 
     * 模擬下載任務,每秒鐘更新一次 
     */  
    public void startDownLoad(){  
        new Thread(new Runnable() {  

            @Override  
            public void run() {  
                while(progress < MAX_PROGRESS){  
                    progress += 5;  

                    //發送Action爲com.example.communication.RECEIVER的廣播  
                    intent.putExtra("progress", progress);  
                    sendBroadcast(intent);  

                    try {  
                        Thread.sleep(1000);  
                    } catch (InterruptedException e) {  
                        e.printStackTrace();  
                    }  

                }  
            }  
        }).start();  
    }  



    @Override  
    public int onStartCommand(Intent intent, int flags, int startId) {  
        startDownLoad();  
        return super.onStartCommand(intent, flags, startId);  
    }  



    @Override  
    public IBinder onBind(Intent intent) {  
        return null;  
    }  


}

總結:

  1. Activity調用bindService (Intent service, ServiceConnection conn, int
    flags)方法,得到Service對象的一個引用,這樣Activity可以直接調用到Service中的方法,如果要主動通知Activity,我們可以利用回調方法
  2. Service向Activity發送消息,可以使用廣播,當然Activity要註冊相應的接收器。比如Service要向多個Activity發送同樣的消息的話,用這種方法就更好
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章