aidl
package xyz.liut.myaidltest;
interface IService {
int plus(int a,int b);
}
server端代码
public class MyServiceTest extends Service {
private IService.Stub stub = new IService.Stub() {
@Override
public int plus(int a, int b) throws RemoteException {
return a + b;
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
return stub;
}
}
<service
android:name=".MyServiceTest"
android:exported="true">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="xyz.liut.aidltest" />
</intent-filter>
</service>
client端
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private IService iService;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iService = IService.Stub.asInterface(service);
Log.e(TAG, "onServiceConnected: " + service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
iService = null;
Log.e(TAG, "onServiceDisconnected: " + name);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setPackage("xyz.liut.myaidltest");
intent.setAction("xyz.liut.aidltest");
bindService(intent, connection, BIND_AUTO_CREATE);
}
public void test(View view) {
try {
if (iService == null) {
Toast.makeText(this, "未绑定远程服务", Toast.LENGTH_SHORT).show();
return;
}
int sum = iService.plus(1, 2);
new AlertDialog.Builder(this)
.setTitle("sum")
.setMessage(Integer.toString(sum))
.setPositiveButton("ok", null)
.show();
} catch (RemoteException e) {
e.printStackTrace();
}
}
网友评论