開發(fā)過程中需要在service中載入一個view,并且在任何頁面內(nèi)都可以向service發(fā)送請求去改變view的顯示馋嗜,由于無法在非主線程中進行UI操作,并且view相關(guān)數(shù)據(jù)在service內(nèi)狮斗,所以必須通過別的方法去操作UI架馋。
廣播
service內(nèi)部自定義一個廣播繼承BroadcastReceiver
class FloatWindowBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//IntentFilter標(biāo)識
if (ACTION_FLOAT.equals(action)){
//傳遞數(shù)據(jù)
String command = intent.getStringExtra("command");
int position = intent.getIntExtra("position",0);
switch (command){
case test:
break;
default:
ToastUtil.showMessage("參數(shù)錯誤");
break;
}
}
}
}
初始化痪署,添加標(biāo)識尸红,注冊廣播纳账。
private FloatWindowBroadcastReceiver floatWindowBroadcastReceiver;
@Override
public void onCreate() {
super.onCreate();
//初始化
floatWindowBroadcastReceiver = new FloatWindowBroadcastReceiver();
//標(biāo)識
IntentFilter filter = new IntentFilter(ACTION_FLOAT);
//注冊廣播
registerReceiver(floatWindowBroadcastReceiver,filter);
}
在service銷毀時取消注冊廣播
@Override
public void onDestroy() {
if (floatWindowBroadcastReceiver != null){
unregisterReceiver(floatWindowBroadcastReceiver);
floatWindowBroadcastReceiver = null;
}
super.onDestroy();
}
在其他頁面內(nèi)調(diào)用該方法操作
Intent intent=new Intent(FloatWindowService.ACTION_FLOAT);
intent.putExtra("command","add");
sendBroadcast(intent);
Handler
service內(nèi)創(chuàng)建一個Handler用于接收消息
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
}
}
};
發(fā)送消息,是否需要啟用線程根據(jù)需求進行操作.
public void send(){
new Thread(new Runnable() {
@Override
public void run() {
Message message=new Message();
Bundle bundle=new Bundle();
message.setData(bundle);
handler.sendMessageDelayed(message,2000);
}).start();
}