请帮我写一些Android代码,要求activity向service传入参数a,b并反回a+b到activity
时间: 2024-05-03 15:20:07 浏览: 65
好的,以下是您所需要的代码:
在Activity中调用Service:
```
Intent intent = new Intent(this, YourService.class);
intent.putExtra("a", a);
intent.putExtra("b", b);
startService(intent);
```
在Service中接收并处理参数:
```
public class YourService extends Service {
private int a, b;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 获取Activity传过来的参数
a = intent.getIntExtra("a", -1);
b = intent.getIntExtra("b", -1);
// 处理参数,比如计算a+b,并反回结果到Activity
int result = a + b;
Intent resultIntent = new Intent();
resultIntent.putExtra("result", result);
setResult(Activity.RESULT_OK, resultIntent);
return super.onStartCommand(intent, flags, startId);
}
}
```
在Activity中接收结果:
```
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
int result = data.getIntExtra("result", -1);
// 处理结果
// ...
}
}
```
注意:`REQUEST_CODE`要自行定义并在启动Service时使用。
阅读全文