新聞中心
之前我們?cè)蚰榻B過(guò)Android的UI設(shè)計(jì)與后臺(tái)線程交互,據(jù)Android API的介紹,service一般是在后臺(tái)運(yùn)行的,沒(méi)有界面的。那么如何實(shí)現(xiàn)service動(dòng)態(tài)更新UI界面呢?

憑祥ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來(lái)市場(chǎng)廣闊!成為成都創(chuàng)新互聯(lián)的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書合作)期待與您的合作!
案例:通過(guò)service向遠(yuǎn)程服務(wù)器發(fā)送請(qǐng)求,根據(jù)服務(wù)器返回的結(jié)果動(dòng)態(tài)更新主程序UI界面,主程序可實(shí)時(shí)關(guān)閉或重啟服務(wù)。
注冊(cè)BroadcastReceiver
在主程序activity中注冊(cè)一個(gè)BroadcastReceiver,用于接收Service發(fā)布的廣播。
- @Override
- protected void onStart() {//重寫onStart方法
- dataReceiver = new DataReceiver();
- IntentFilter filter = new IntentFilter();//創(chuàng)建IntentFilter對(duì)象
- filter.addAction("com.justel.serviceBC");
- registerReceiver(dataReceiver, filter);//注冊(cè)Broadcast Receiver
- super.onStart();
- }
停止service命令
主程序activity可發(fā)布廣播,用于向后臺(tái)service傳遞數(shù)據(jù)或控制信息,如停止service命令。
- btnStop.setOnClickListener(new OnClickListener() {//為按鈕添加點(diǎn)擊事件監(jiān)聽
- @Override
- public void onClick(View v) {//重寫onClick方法
- Intent myIntent = new Intent();//創(chuàng)建Intent對(duì)象
- myIntent.setAction("com.justel.service");
- myIntent.putExtra("cmd", CMD_STOP_SERVICE);
- sendBroadcast(myIntent);//發(fā)送廣播
- }
- });
接收廣播
后臺(tái)service注冊(cè)BroadCastReceiver用于接受主程序發(fā)送的廣播
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {//重寫onStartCommand方法
- IntentFilter filter = new IntentFilter();//創(chuàng)建IntentFilter對(duì)象
- filter.addAction("com.justel.service");
- registerReceiver(cmdReceiver, filter);//注冊(cè)Broadcast Receiver
- doJob();//調(diào)用方法啟動(dòng)線程,自己來(lái)完成
- return super.onStartCommand(intent, flags, startId);
- }
實(shí)時(shí)發(fā)送
后臺(tái)service在doJob()方法中連接服務(wù)器并向主程序?qū)崟r(shí)發(fā)送廣播。
- /**
- * 啟動(dòng)一個(gè)子純種并連接服務(wù)器,接收服務(wù)器返回?cái)?shù)據(jù)data。代碼略。。。
- */
- Object data;//服務(wù)器返回的數(shù)據(jù)data
- Intent intent = new Intent();//創(chuàng)建Intent對(duì)象
- intent.setAction("com.justel.service");
- intent.putExtra("data", data);
- sendBroadcast(intent);//發(fā)送廣播
至此,我們實(shí)現(xiàn)了主程序通過(guò)接收廣播實(shí)時(shí)更新應(yīng)用的UI界面。
當(dāng)前標(biāo)題:在Android中實(shí)現(xiàn)service動(dòng)態(tài)更新UI界面
網(wǎng)頁(yè)網(wǎng)址:http://m.5511xx.com/article/cdgjjoj.html
其他資訊
- 使用Redis端口號(hào)連接的簡(jiǎn)單操作(redis端口號(hào)連接)
- 為啥選擇vps主機(jī)搭建網(wǎng)站不能用
- 啟動(dòng)風(fēng)行時(shí),提示網(wǎng)絡(luò)中斷,請(qǐng)檢查網(wǎng)絡(luò)連接是怎么回事?(網(wǎng)絡(luò)中斷無(wú)法訪問(wèn)請(qǐng)修復(fù))
- Redis實(shí)現(xiàn)多少并發(fā)能力(一個(gè)redis多少個(gè)并發(fā))
- Linux驅(qū)動(dòng)移植:輕松實(shí)現(xiàn)硬件兼容性(linux驅(qū)動(dòng)移植)


咨詢
建站咨詢
