Service AIDL总结
2019-03-05 本文已影响0人
梦里风吹过
基于Android Studio。
服务端
1. 创建aidl文件
创建文件 创建成功示例
interface AppCheckInterface {
boolean checkApp(String identify);
}
2. 创建Service文件。
新建为普通Java类文件,展示如下:
service
代码:
public class AppCheckService extends Service {
final String IDENTIFY = "12345678";
@Override
public IBinder onBind(Intent intent) {
return binder;
}
private final AppCheckInterface.Stub binder = new AppCheckInterface.Stub() {
@Override
public boolean checkApp(String identify) throws RemoteException {
return TextUtils.equals(IDENTIFY,identify);
}
};
}
3. 配置(重要)
<service android:name=".AppCheckService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.ceshi.aidltest.AppCheckService" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</service>
4. 本APP使用示例
class MainActivity : AppCompatActivity() {
internal var appCheckInterface: AppCheckInterface? = null
internal var serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
appCheckInterface = AppCheckInterface.Stub.asInterface(service)
if (appCheckInterface != null) {
try {
Log.e("结果", "" + appCheckInterface!!.checkApp("12345678"))
} catch (e: RemoteException) {
e.printStackTrace()
Log.e("结果", "出错")
}
} else {
Log.e("结果", "出错 null")
}
}
override fun onServiceDisconnected(name: ComponentName) {
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val intent = Intent(this,AppCheckService ::class.java)
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
override fun onDestroy() {
super.onDestroy()
unbindService(serviceConnection)
}
}
客户端
1. 创建aidl文件,创建过程与服务端相同,但是由于自动生成包名不同,需要改包名。
aidl文件注意:aidl文件包名许与服务端相同,文件内容和服务端相同(可直接从服务端复制过来)
2. 使用示例:
interface AppCheckInterface {
boolean checkApp(String identify);
}
public class MainActivity extends AppCompatActivity {
AppCheckInterface appCheckInterface;
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
appCheckInterface = AppCheckInterface.Stub.asInterface(service);
if (appCheckInterface!=null){
try {
Log.e("结果",""+ appCheckInterface.checkApp("HhZ8yhiDrow3c3lz"));
} catch (RemoteException e) {
e.printStackTrace();
Log.e("结果","出错");
}
}else {
Log.e("结果","出错 null");
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
//这里action和包名需要和服务端对应。
intent.setAction("com.ceshi.aidltest.AppCheckService");
intent.setPackage("com.ceshi.aidltest");
bindService(intent,serviceConnection,BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
}
注:使用过程中需先安装服务端APP,客户端使用过程中,只需保证服务端已安装即可,可以不在服务端手动启动service。