2011.07.13——— android remote service bind
参考:
http://blog.csdn.net/saintswordsman/article/details/5130947
http://www.imobilebbs.com/wordpress/?p=1265
Android Interface Definition Language(AIDL)和其它一些支持远程方法调用RMI的系统的IDL类似,它定义了Service和Client 之间的使用接口约定,这种远程调用一般需要通过进程间通信机制(IPC)来实现。在Android系统,一个进程(Process)通常不能直接访问其它进程的内存空间,Android系统支持使用AIDL来实现使用不同进程间调用服务接口
AIDL接口定义使用Java Interface语法定义在 .aidl文件中,然后必须同时放在Service和Client 的 src目录下。 当使用Eclipse 编译时,Android SDK工具会根据 .aidl的接口定义自动生成对应的IBinder接口定义 (定义在gen目录下) Service必须实现由这个IBinder接口定义。 Client然后可以通过绑定Service来访问这些方法。
1. 创建. aidl 文件
本例有两个
IRemoteService
package com.example.android.apis.app;
import com.example.android.apis.app.IRemoteServiceCallback;
/**
* Example of defining an interface for calling on to a remote service
* (running in another process).
*/
interface IRemoteService {
void registerCallback(IRemoteServiceCallback cb);
/**
* Remove a previously registered callback interface.
*/
void unregisterCallback(IRemoteServiceCallback cb);
}
IRemoteServiceCallback
package com.example.android.apis.app;
oneway interface IRemoteServiceCallback {
/**
* Called when the service has a new value for you.
*/
void valueChanged(int value);
}
2. service
public class RemoteService extends Service {
/**
* This is a list of callbacks that have been registered with the
* service. Note that this is package scoped (instead of private) so
* that it can be accessed more efficiently from inner classes.
*/
final RemoteCallbackList<IRemoteServiceCallback> mCallbacks
= new RemoteCallbackList<IRemoteServiceCallback>();
int mValue = 0;
NotificationManager mNM;
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting.
showNotification();
// While this service is running, it will continually increment a
// number. Send the first message that is used to perform the
// increment.
System.out.println("create start");
mHandler.sendEmptyMessage(REPORT_MSG);
System.out.println("create end");
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(R.string.remote_service_started);
// Tell the user we stopped.
Toast.makeText(this, R.string.remote_service_stopped, Toast.LENGTH_SHORT).show();
// Unregister all callbacks.
mCallbacks.kill();
// Remove the next pending message to increment the counter, stopping
// the increment loop.
mHandler.removeMessages(REPORT_MSG);
}
@Override
public IBinder onBind(Intent intent) {
// Select the interface to return. If your service only implements
// a single interface, you can just return it here without checking
// the Intent.
System.out.println("bind");
if (IRemoteService.class.getName().equals(intent.getAction())) {
return mBinder;
}
if (ISecondary.class.getName().equals(intent.getAction())) {
return mSecondaryBinder;
}
return null;
}
/**
* The IRemoteInterface is defined through IDL
*/
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public void registerCallback(IRemoteServiceCallback cb) {
if (cb != null) mCallbacks.register(cb);
}
public void unregisterCallback(IRemoteServiceCallback cb) {
if (cb != null) mCallbacks.unregister(cb);
}
};
private static final int REPORT_MSG = 1;
/**
* Our Handler used to execute operations on the main thread. This is used
* to schedule increments of our value.
*/
private final Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
// It is time to bump the value!
case REPORT_MSG: {
// Up it goes.
int value = ++mValue;
// Broadcast to all clients the new value.
final int N = mCallbacks.beginBroadcast();
System.out.println("handler "+N);
for (int i=0; i<N; i++) {
try {
mCallbacks.getBroadcastItem(i).valueChanged(value);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing
// the dead object for us.
}
}
mCallbacks.finishBroadcast();
// Repeat every 1 second.
sendMessageDelayed(obtainMessage(REPORT_MSG), 1*1000);
} break;
default:
super.handleMessage(msg);
}
}
};
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.remote_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, Controller.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
text, contentIntent);
// Send the notification.
// We use a string id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.remote_service_started, notification);
}
3、activity端
public static class Binding extends Activity {
/** The primary interface we will be calling on the service. */
IRemoteService mService = null;
/** Another interface we use on the service. */
ISecondary mSecondaryService = null;
Button mKillButton;
TextView mCallbackText;
private boolean mIsBound;
/**
* Standard initialization of this activity. Set up the UI, then wait
* for the user to poke it before doing anything.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remote_service_binding);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.bind);
button.setOnClickListener(mBindListener);
button = (Button)findViewById(R.id.unbind);
button.setOnClickListener(mUnbindListener);
mKillButton = (Button)findViewById(R.id.kill);
mKillButton.setOnClickListener(mKillListener);
mKillButton.setEnabled(false);
mCallbackText = (TextView)findViewById(R.id.callback);
mCallbackText.setText("Not attached.");
}
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
mService = IRemoteService.Stub.asInterface(service);
mKillButton.setEnabled(true);
mCallbackText.setText("Attached.");
// We want to monitor the service for as long as we are
// connected to it.
try {
mService.registerCallback(mCallback);
} catch (RemoteException e) {
}
// As part of the sample, tell the user what happened.
Toast.makeText(Binding.this, R.string.remote_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
mKillButton.setEnabled(false);
mCallbackText.setText("Disconnected.");
// As part of the sample, tell the user what happened.
Toast.makeText(Binding.this, R.string.remote_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
private OnClickListener mBindListener = new OnClickListener() {
public void onClick(View v) {
bindService(new Intent(IRemoteService.class.getName()),
mConnection, Context.BIND_AUTO_CREATE);
bindService(new Intent(ISecondary.class.getName()),
mSecondaryConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
mCallbackText.setText("Binding.");
}
};
private OnClickListener mUnbindListener = new OnClickListener() {
public void onClick(View v) {
if (mIsBound) {
// If we have received the service, and hence registered with
// it, then now is the time to unregister.
if (mService != null) {
try {
mService.unregisterCallback(mCallback);
} catch (RemoteException e) {
// There is nothing special we need to do if the service
// has crashed.
}
}
// Detach our existing connection.
unbindService(mConnection);
unbindService(mSecondaryConnection);
mKillButton.setEnabled(false);
mIsBound = false;
mCallbackText.setText("Unbinding.");
}
}
};
private OnClickListener mKillListener = new OnClickListener() {
public void onClick(View v) {
// To kill the process hosting our service, we need to know its
// PID. Conveniently our service has a call that will return
// to us that information.
if (mSecondaryService != null) {
try {
int pid = mSecondaryService.getPid();
Process.killProcess(pid);
mCallbackText.setText("Killed service process.");
} catch (RemoteException ex) {
// Recover gracefully from the process hosting the
// server dying.
// Just for purposes of the sample, put up a notification.
Toast.makeText(Binding.this,
R.string.remote_call_failed,
Toast.LENGTH_SHORT).show();
}
}
}
};
// ----------------------------------------------------------------------
// Code showing how to deal with callbacks.
// ----------------------------------------------------------------------
/**
* This implementation is used to receive callbacks from the remote
* service.
*/
private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
public void valueChanged(int value) {
mHandler.sendMessage(mHandler.obtainMessage(BUMP_MSG, value, 0));
}
};
private static final int BUMP_MSG = 1;
private Handler mHandler = new Handler() {
@Override public void handleMessage(Message msg) {
switch (msg.what) {
case BUMP_MSG:
mCallbackText.setText("Received from service: " + msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
};
}
大致流程图:
- 大小: 76.7 KB
分享到:
相关推荐
javax.xml.bind.jar
Unable to load class ‘javax.xml.bind.JAXBException‘(csdn)
赠送jar包:jakarta.xml.bind-api-2.3.3.jar; 赠送原API文档:jakarta.xml.bind-api-2.3.3-javadoc.jar; 赠送源代码:jakarta.xml.bind-api-2.3.3-sources.jar; 赠送Maven依赖信息文件:jakarta.xml.bind-api-...
在集成阿里云移动推送时,部署到服务器的时候遇到了java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter 错误,产生原因是缺少javax.xml.bind.DatatypeConverter
赠送jar包:jakarta.xml.bind-api-2.3.3.jar; 赠送原API文档:jakarta.xml.bind-api-2.3.3-javadoc.jar; 赠送源代码:jakarta.xml.bind-api-2.3.3-sources.jar; 赠送Maven依赖信息文件:jakarta.xml.bind-api-...
javax.xml.bind.jar和三个sqljdbc4x.jar;实测可用。用于sqlserver连接和出现Java 9 及以上 eclipse 链接 SQL数据库 抛出 java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter 异常
java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter 错误,产生原因是缺少javax.xml.bind.DatatypeConverter
赠送jar包:jakarta.xml.bind-api-2.3.2.jar; 赠送原API文档:jakarta.xml.bind-api-2.3.2-javadoc.jar; 赠送源代码:jakarta.xml.bind-api-2.3.2-sources.jar; 赠送Maven依赖信息文件:jakarta.xml.bind-api-...
java运行依赖jar包
最近在学习Spring MVC 时候遇到了NoClassDefFoundError: javax/xml/bind/JAXBException 错误,产生原因是缺少javax.xml.bind Jar包.
java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory jdk1.5
javax.xml.bind_2.1.9.v201005080401.jar
主要解决Java连接Sql Server报错:Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter 另外赠送一个Sql 的jdbc驱动
Apress.Pro.DNS.and.BIND.10.Feb.201 又一本关于dns的书籍。
jar包,官方版本,自测可用
赠送jar包:jakarta.xml.bind-api-2.3.2.jar; 赠送原API文档:jakarta.xml.bind-api-2.3.2-javadoc.jar; 赠送源代码:jakarta.xml.bind-api-2.3.2-sources.jar; 赠送Maven依赖信息文件:jakarta.xml.bind-api-...
包含以下java源文件: ...com.google.gson.internal.bind.CollectionTypeAdapterFactory.class com.google.gson.internal.bind.DateTypeAdapter.class com.google.gson.internal.bind.JsonTreeReader.class ...
jar包,官方版本,自测可用