开发过程中需要在service中载入一个view,并且在任何页面内都可以向service发送请求去改变view的显示,由于无法在非主线程中进行UI操作,并且view相关数据在service内,所以必须通过别的方法去操作UI。
广播
service内部自定义一个广播继承BroadcastReceiver
class FloatWindowBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//IntentFilter标识
if (ACTION_FLOAT.equals(action)){
//传递数据
String command = intent.getStringExtra("command");
int position = intent.getIntExtra("position",0);
switch (command){
case test:
break;
default:
ToastUtil.showMessage("参数错误");
break;
}
}
}
}
初始化,添加标识,注册广播。
private FloatWindowBroadcastReceiver floatWindowBroadcastReceiver;
@Override
public void onCreate() {
super.onCreate();
//初始化
floatWindowBroadcastReceiver = new FloatWindowBroadcastReceiver();
//标识
IntentFilter filter = new IntentFilter(ACTION_FLOAT);
//注册广播
registerReceiver(floatWindowBroadcastReceiver,filter);
}
在service销毁时取消注册广播
@Override
public void onDestroy() {
if (floatWindowBroadcastReceiver != null){
unregisterReceiver(floatWindowBroadcastReceiver);
floatWindowBroadcastReceiver = null;
}
super.onDestroy();
}
在其他页面内调用该方法操作
Intent intent=new Intent(FloatWindowService.ACTION_FLOAT);
intent.putExtra("command","add");
sendBroadcast(intent);
Handler
service内创建一个Handler用于接收消息
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
}
}
};
发送消息,是否需要启用线程根据需求进行操作.
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();
}
网友评论