Android - 在活动中使用服务的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2272378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android - Using method from a Service in an Activity?
提问by Donal Rafferty
I have the folowing method in a Service in my appplication:
我的应用程序中的服务中有以下方法:
public void switchSpeaker(boolean speakerFlag){
if(speakerFlag){
audio_service.setSpeakerphoneOn(false);
}
else{
audio_service.setSpeakerphoneOn(true);
}
}
So my question is whats the best and most effective way to be able to use this method in an Activity like follows
所以我的问题是能够在如下活动中使用这种方法的最佳和最有效的方法是什么
final Button speaker_Button = (Button) findViewById(R.id.widget36);
speaker_Button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
switchSpeaker(true); //method from Service
}
});
Do I have to do an AIDL or is there a simpler way?
我必须做一个 AIDL 还是有更简单的方法?
采纳答案by ponkin
You have to expose service`s switchSpeakermethod for clients. Define your .aidl file. Than bind to that service from your activity and simply call switchSpeaker. See documentation
您必须为客户端公开服务的switchSpeaker方法。定义您的 .aidl 文件。比从您的活动绑定到该服务并简单地调用switchSpeaker。查看文档
No other simple way to call this method, only if it static)
没有其他简单的方法来调用这个方法,只有当它是静态的)
回答by Dharmendra
There are 3 ways to binding service with your activity.
有 3 种方法可以将服务与您的活动绑定。
- IBinder Implementation
- Using Messanger
- Using AIDL
- IBinder 实现
- 使用信使
- 使用 AIDL
Among these IBinder Implementation is the best suit in your case
在这些 IBinder 实现中,最适合您的情况
Example of IBinder class
IBinder 类示例
1. Server.java Service
1.Server.java 服务
public class Server extends Service{
IBinder mBinder = new LocalBinder();
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public Server getServerInstance() {
return Server.this;
}
}
public void switchSpeaker(boolean speakerFlag){
if(speakerFlag){
audio_service.setSpeakerphoneOn(false);
}
else{
audio_service.setSpeakerphoneOn(true);
}
}
}
2. Client.java Activity
2. Client.java 活动
public class Client extends Activity {
boolean mBounded;
Server mServer;
TextView text;
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mServer.switchSpeaker(true);
}
});
}
@Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, Server.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
};
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(Client.this, "Service is disconnected", 1000).show();
mBounded = false;
mServer = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(Client.this, "Service is connected", 1000).show();
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder)service;
mServer = mLocalBinder.getServerInstance();
}
};
@Override
protected void onStop() {
super.onStop();
if(mBounded) {
unbindService(mConnection);
mBounded = false;
}
};
}
Example of Messanger class
信使类示例
1. Server.java service
1.Server.java服务
public class Server extends Service{
Messenger messenger = new Messenger(new LocalHandler());
Messenger clientMessenger;
static final int SysterTime = 0;
static final int AddHandler = 1;
List<Handler> mHandlers;
@Override
public void onCreate() {
super.onCreate();
mHandlers = new ArrayList<Handler>();
}
@Override
public IBinder onBind(Intent intent) {
return messenger.getBinder();
}
public class LocalHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SysterTime:
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
clientMessenger.send(Message.obtain(null, SysterTime, mDateFormat.format(new Date())));
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case AddHandler:
clientMessenger = new Messenger((Handler) msg.obj);
try {
clientMessenger.send(Message.obtain(null, AddHandler, "Registed messanger"));
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
break;
}
super.handleMessage(msg);
}
}
}
2. Client.java Activity
2. Client.java 活动
public class Client extends Activity {
Messenger messenger;
boolean mBounded;
TextView text;
Button button;
Button register;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Message message = Message.obtain(null, Server.SysterTime, null);
try {
messenger.send(message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
register = (Button) findViewById(R.id.register);
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Message message = Message.obtain(null, Server.AddHandler, new ClientHandle());
try {
messenger.send(message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class ClientHandle extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Server.SysterTime:
text.setText(msg.obj.toString());
break;
case Server.AddHandler:
text.setText(msg.obj.toString());
break;
default:
break;
}
super.handleMessage(msg);
}
}
@Override
protected void onStart() {
super.onStart();
bindService(new Intent(this, Server.class), mConnection, BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if(mBounded) {
unbindService(mConnection);
}
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
mBounded = false;
messenger = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(Client.this, "Service is connected", 1000).show();
messenger = new Messenger(service);
mBounded = true;
}
};
}
Example of AIDL
AIDL 示例
1. IRemoteService.aidl
1.IRemoteService.aidl
package com.example.bindservice.aidl;
interface IRemoteService {
String getMessage(String msg);
}
2. Server.java Service
2.Server.java 服务
public class Server extends Service{
@Override
public IBinder onBind(Intent intent) {
return mStub;
}
IRemoteService.Stub mStub = new IRemoteService.Stub() {
public String getMessage(String msg) throws RemoteException {
return msg;
}
};
}
3. Client.java Activity
3. Client.java 活动
public class Client extends Activity {
Button button;
TextView text;
boolean mBound;
IRemoteService mIRemoteService;
EditText etMsg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
etMsg = (EditText)findViewById(R.id.etMsg);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(mBound) {
try {
text.setText(mIRemoteService.getMessage(etMsg.getText().toString()));
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
});
}
@Override
protected void onStart() {
super.onStart();
bindService(new Intent(Client.this, Server.class), mConnection, BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if(mBound) {
unbindService(mConnection);
mBound = false;
}
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
mIRemoteService = null;
mBound = false;
}
public void onServiceConnected(ComponentName name, IBinder service) {
mIRemoteService = IRemoteService.Stub.asInterface(service);
mBound = true;
}
};
}
For more study you can refer this document
有关更多研究,您可以参考此文档
回答by Binh Tran
It's public, right :)
这是公开的,对:)
You can call bindService(Intent) method. Tale a look at ApiDemos, the class LocalServiceBinding.
您可以调用 bindService(Intent) 方法。看看 ApiDemos,LocalServiceBinding 类。
In the callback method onServiceConnected, you can see:
在onServiceConnected的回调方法中,可以看到:
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((LocalService.LocalBinder)service).getService();
// Tell the user about this for our demo.
Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
Now, use the service object (mBoundService) to call the method.
现在,使用服务对象 (mBoundService) 来调用该方法。
That's all :)
就这样 :)