在Android中實現service動態更新UI介面

來源:互聯網
上載者:User
 

之前我們曾向您介紹過Android的UI設計與後台線程互動,據Android API的介紹,service一般是在後台啟動並執行,沒有介面的。那麼如何?service動態更新UI介面呢。

案例:通過service向遠程伺服器發送請求,根據伺服器返回的結果動態更新主程式UI介面,主程式可即時關閉或重啟服務。 註冊BroadcastReceiver

在主程式activity中註冊一個BroadcastReceiver,用於接收Service發布的廣播。

 @Override  protected void onStart() {//重寫onStart方法       dataReceiver = new DataReceiver();       IntentFilter filter = new IntentFilter();//建立IntentFilter對象       filter.addAction("com.justel.serviceBC");       registerReceiver(dataReceiver, filter);//註冊Broadcast Receiver       super.onStart();   }  
停止service命令 

主程式activity可發布廣播,用於向後台service傳遞資料或控制資訊,如停止service命令。

       btnStop.setOnClickListener(new OnClickListener() {//為按鈕添加點擊事件監聽          @Override      public void onClick(View v) {//重寫onClick方法           Intent myIntent = new Intent();//建立Intent對象           myIntent.setAction("com.justel.service");           myIntent.putExtra("cmd", CMD_STOP_SERVICE);           sendBroadcast(myIntent);//發送廣播       }   });  
接收廣播 

後台service註冊BroadCastReceiver用於接受主程式發送的廣播

 @Override  public int onStartCommand(Intent intent, int flags, int startId) {//重寫onStartCommand方法       IntentFilter filter = new IntentFilter();//建立IntentFilter對象       filter.addAction("com.justel.service");       registerReceiver(cmdReceiver, filter);//註冊Broadcast Receiver       doJob();//調用方法啟動線程,自己來完成       return super.onStartCommand(intent, flags, startId);   }  
即時發送  

後台service在doJob()方法中串連伺服器並向主程式即時發送廣播。

 /**    * 啟動一個子純種並串連伺服器,接收伺服器返回資料data。代碼略。。。    */  Object data;//伺服器返回的資料data   Intent intent = new Intent();//建立Intent對象   intent.setAction("com.justel.service");   intent.putExtra("data", data);   sendBroadcast(intent);//發送廣播  

至此,我們實現了主程式通過接收廣播即時更新應用的UI介面。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.