Java 从线程绑定服务
可以从线程将服务绑定到服务吗 我尝试向正在运行的服务传递一个字符串,然后运行一个方法来显示通知 知道正确的方法是什么吗Java 从线程绑定服务,java,android,android-intent,android-service,android-service-binding,Java,Android,Android Intent,Android Service,Android Service Binding,可以从线程将服务绑定到服务吗 我尝试向正在运行的服务传递一个字符串,然后运行一个方法来显示通知 知道正确的方法是什么吗 提前谢谢。请您尝试以下方法: 首先编写服务类 然后写你的活动课 我是从中得到这个想法的。如果我没有参加活动呢。如果wan不从非活动绑定服务,该怎么办?有可能吗?我解决了。但你告诉我答案的主要意思。非常感谢。 public class ShowNotifyService extends Service { private Messenger msg = new Mess
提前谢谢。请您尝试以下方法: 首先编写服务类 然后写你的活动课
我是从中得到这个想法的。如果我没有参加活动呢。如果wan不从非活动绑定服务,该怎么办?有可能吗?我解决了。但你告诉我答案的主要意思。非常感谢。
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);
}
}
}
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
}
}
}
}
}