是否可以从线程将服务绑定到服务?
我尝试将一个字符串传递给正在运行的服务,并运行一个方法来显示通知?
知道什么是正确的方法吗?
提前致谢。
是否可以从线程将服务绑定到服务?
我尝试将一个字符串传递给正在运行的服务,并运行一个方法来显示通知?
知道什么是正确的方法吗?
提前致谢。
愿你这样尝试:首先写你的Service
课。
public class ShowNotifyService extends Service {
private Messenger msg = new Messenger(new ShowNotifyHanlder());
@Override
public IBinder onBind(Intent arg0) {
return msg.getBinder();
}
class ShowNotifyHanlder extends Handler {
@Override
public void handleMessage(Message msg) {
// This is the action
int msgType = msg.what;
switch(msgType) {
case SHOW_FIRST_NOTIFY: {
try {
// Incoming data
String data = msg.getData().getString("data");
Message resp = Message.obtain(null, SHOW_FIRST_NOTIFY_RESPONSE);
Bundle bResp = new Bundle();
bResp.putString("respData", first_notify_data);// here you set the data you want to show
resp.setData(bResp);
msg.replyTo.send(resp);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
}
default:
super.handleMessage(msg);
}
}
}
然后写你的Activity
课。
public class TestActivity {
..
private ServiceConnection sConn;
private Messenger messenger;
..
@Override
protected void onCreate(Bundle savedInstanceState) {
// Service Connection to handle system callbacks
sConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
messenger = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We are conntected to the service
messenger = new Messenger(service);
}
};
...
// We bind to the service
bindService(new Intent(this, ShowNotifyService.class), sConn,
Context.BIND_AUTO_CREATE);
..
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String val = edt.getText().toString();
Message msg = Message.obtain(null, ShowNotifyService.SHOW_FIRST_NOTIFY);
msg.replyTo = new Messenger(new ResponseHandler());
// We pass the value
Bundle b = new Bundle();
b.putString("data", val);
msg.setData(b);
try {
messenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
// This class handles the Service response
class ResponseHandler extends Handler {
@Override
public void handleMessage(Message msg) {
int respCode = msg.what;
switch (respCode) {
case ShowNotifyService.SHOW_FIRST_NOTIFY_RESPONSE: {
result = msg.getData().getString("respData");
//then you show the result data from service here
}
}
}
}
}
我从这里得到了这个想法。