Android系统应用层软件设计设计一个Service提供a+b计算服务,再设计另一个APP跨进程访问a+b服务的代码
时间: 2024-03-13 08:42:28 浏览: 60
编写Android Service服务的一个源码例子
好的,下面是具体的代码实现:
AdditionService.java
```java
public class AdditionService extends Service {
private final IBinder binder = new AdditionBinder();
public class AdditionBinder extends Binder {
public int add(int a, int b) {
return a + b;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
}
```
AdditionServiceConnection.java
```java
public class AdditionServiceConnection implements ServiceConnection {
private AdditionService.AdditionBinder binder;
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
binder = (AdditionService.AdditionBinder) iBinder;
int result = binder.add(2, 3); // 调用a+b计算服务
Log.d("AdditionService", "result: " + result);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
```
MainActivity.java
```java
public class MainActivity extends AppCompatActivity {
private AdditionServiceConnection connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button calculateButton = findViewById(R.id.calculate_button);
calculateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AdditionService.class);
connection = new AdditionServiceConnection();
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (connection != null) {
unbindService(connection);
}
}
}
```
以上代码实现了在一个APP中实现跨进程访问a+b计算服务的功能。在另一个APP中也可以通过相同的方式进行访问。
阅读全文