android11 native binder service入门之创建一个自己的service

下面创建了一个名称为"test.binderLib.0921“的 service,并通过defaultServiceManager增加到系统的服务中。我们这个服务的功能是读取客户发过来的2个整型值然后计算出和后返回给客户端。

#include <ui/DisplayConfig.h>

#include <gui/IRegionSamplingListener.h>
#include <gui/ISurfaceComposer.h>
#include <gui/SurfaceControl.h>
#include <gui/Surface.h>
#include <private/gui/ComposerService.h>
#include <gui/SurfaceComposerClient.h>
#include <android/native_window.h>
#include <utils/Trace.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <iostream>
#include <stdint.h>
#include <sys/types.h>
#include <set>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <inttypes.h>

#include <cutils/properties.h>
#include <utils/Log.h>
#include <utils/SystemClock.h>
#include <android-base/properties.h>
#include <errno.h>
#include <fcntl.h>
#include <fstream>
#include <poll.h>
#include <pthread.h>

#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/Binder.h>
#include <binder/IBinder.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/IServiceManager.h>

#include <private/binder/binder_module.h>
#include <sys/epoll.h>
#include <sys/prctl.h>

using namespace android;
using namespace std;

enum BinderLibTestTranscationCode {
	BINDER_LIB_TEST_SUM_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,

};

class BinderLibTestService: public BBinder {
public:
	explicit BinderLibTestService(int32_t id)
			{

	}
	~BinderLibTestService() {
		exit(EXIT_SUCCESS);
	}

	virtual status_t onTransact(uint32_t code, const Parcel &data,
			Parcel *reply, uint32_t flags = 0) override  {
		//printf("%s: code %d\n", __func__, code);
		(void) flags;

		if (getuid() != (uid_t) IPCThreadState::self()->getCallingUid()) {
			return PERMISSION_DENIED;
		}
		switch (code) {
		case BINDER_LIB_TEST_SUM_TRANSACTION:
			cout
					<< "BinderLibTestService onTransact BINDER_LIB_TEST_NOP_TRANSACTION"
					<< endl;
			int32_t a,b;
			a = data.readInt32();
			b = data.readInt32();
			cout<<"a : " <<a<< endl ;
			cout<<"b : " <<b<< endl ;
			reply->writeInt32(a+b);
			return NO_ERROR;
		default:
			return UNKNOWN_TRANSACTION;
		};
	}

};

static String16 binderLibTestServiceName = String16("test.binderLib.0921");

int main(int /*argc*/, char** /*argv*/) {
	sp < IBinder > m_server;
	status_t ret;
	sp < IServiceManager > sm = defaultServiceManager();
	ProcessState::self()->startThreadPool();

	sp<BinderLibTestService> testService = new BinderLibTestService(0);

	ret = sm->addService(binderLibTestServiceName, testService);

//	m_server = sm->getService(binderLibTestServiceName);
//
//	Parcel data, reply;
//
//	data.writeInt32(40);
//	data.writeInt32(50);
//	ret = m_server->transact(BINDER_LIB_TEST_SUM_TRANSACTION, data, &reply);
//
//	cout << ret << endl;
//	cout << reply.readInt32() << endl;

	printf("end\n");
	IPCThreadState::self()->joinThreadPool();
	return 0;
}

下面是另外的独立的一个应用程序作为客户端,,这个客户端从系统的defaultServiceManager中获取名称为"test.binderLib.0921“的服务,然后发送2个整型,并获取返回结果。

#include <ui/DisplayConfig.h>

#include <gui/IRegionSamplingListener.h>
#include <gui/ISurfaceComposer.h>
#include <gui/SurfaceControl.h>
#include <gui/Surface.h>
#include <private/gui/ComposerService.h>
#include <gui/SurfaceComposerClient.h>
#include <android/native_window.h>
#include <utils/Trace.h>
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <iostream>
#include <stdint.h>
#include <sys/types.h>
#include <set>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <inttypes.h>

#include <cutils/properties.h>
#include <utils/Log.h>
#include <utils/SystemClock.h>
#include <android-base/properties.h>
#include <errno.h>
#include <fcntl.h>
#include <fstream>
#include <poll.h>
#include <pthread.h>

#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/Binder.h>
#include <binder/IBinder.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/IServiceManager.h>

#include <private/binder/binder_module.h>
#include <sys/epoll.h>
#include <sys/prctl.h>

using namespace android;
using namespace std;

enum BinderLibTestTranscationCode {
	BINDER_LIB_TEST_SUM_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
};

static String16 binderLibTestServiceName = String16("test.binderLib.0921");

int main(int /*argc*/, char** /*argv*/) {
	sp < IBinder > m_server;
	status_t ret;
	sp <IServiceManager> sm = defaultServiceManager();
	ProcessState::self()->startThreadPool();

	m_server = sm->getService(binderLibTestServiceName);

	Parcel data, reply;

	data.writeInt32(40);
	data.writeInt32(50);
	ret = m_server->transact(BINDER_LIB_TEST_SUM_TRANSACTION, data, &reply);

	cout << ret << endl;
	cout << reply.readInt32() << endl;

	printf("end\n");
	IPCThreadState::self()->joinThreadPool();
	return 0;
}

运行之后会打印90,说明是成功的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的 Android Binder Demo。 首先,我们定义一个 AIDL 接口文件 `IDemoService.aidl`,它包含一个方法 `int add(int a, int b)`,用于计算两个整数的和。 ```aidl // IDemoService.aidl interface IDemoService { int add(int a, int b); } ``` 然后,我们实现这个接口,创建一个名为 `DemoService` 的服务类,它继承自 `IDemoService.Stub`,实现 `add()` 方法。 ```java // DemoService.java public class DemoService extends IDemoService.Stub { @Override public int add(int a, int b) throws RemoteException { return a + b; } } ``` 接下来,我们创建一个 `Service` 类 `DemoServiceClass`,并在其中实现 `onBind()` 方法,返回 `DemoService` 对象。 ```java // DemoServiceClass.java public class DemoServiceClass extends Service { private DemoService demoService; @Override public void onCreate() { super.onCreate(); demoService = new DemoService(); } @Nullable @Override public IBinder onBind(Intent intent) { return demoService; } } ``` 最后,在 `AndroidManifest.xml` 中声明服务。 ```xml <!-- AndroidManifest.xml --> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.binderdemo"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <!-- 声明 DemoServiceClass --> <service android:name=".DemoServiceClass" /> <activity android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBar"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> ``` 现在,我们可以在 `MainActivity` 中创建一个远程服务连接,调用 `add()` 方法并显示结果。 ```java // MainActivity.java public class MainActivity extends AppCompatActivity { private IDemoService demoService; private boolean connected = false; private ServiceConnection connection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { demoService = IDemoService.Stub.asInterface(iBinder); connected = true; } @Override public void onServiceDisconnected(ComponentName componentName) { demoService = null; connected = false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this, DemoServiceClass.class); bindService(intent, connection, Context.BIND_AUTO_CREATE); Button button = findViewById(R.id.button); final TextView result = findViewById(R.id.result); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (connected) { try { int a = Integer.parseInt(((EditText) findViewById(R.id.input1)).getText().toString()); int b = Integer.parseInt(((EditText) findViewById(R.id.input2)).getText().toString()); int sum = demoService.add(a, b); result.setText(String.valueOf(sum)); } catch (RemoteException e) { e.printStackTrace(); } } else { result.setText("Service not connected"); } } }); } @Override protected void onDestroy() { super.onDestroy(); unbindService(connection); } } ``` 这就是一个简单的 Android Binder Demo。它演示了如何创建一个远程服务,实现 AIDL 接口并将其绑定到 Activity。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值