Android—service,AIDL实现进程间的通信并传递复杂数据类型案例分享

Service:

service是安卓四大组件之一,是一种可在后台执行长时间运行操作而不提供界面的应用组件,即便用户将应用切换到了后台,服务依旧可以正常运行,服务可由其他应用组件(例如Activity)启动。

AIDL: 接口定义语言

由于在Android中进程间无法共享内存(进程隔离),AIDL就是用于两个进程间通信的工具。

实例分享:

实现进程间的通信,A应用实现一个服务,服务里有两个方法,B应用绑定调用A应用的服务,并调用两个方法sayHello和sayHelloTo,其中sayHelloTo方法为传递复杂数据类型。

方法1:public String sayHello(){
        return "你好,我是A应用";
    }

方法2: public Personal sayHelloTo(String name,boolean sex,int age){
        return new Personal(name,sex,age);
    }

相关代码如下:

 应用A的MainActivity.java:

package com.example.myeverytest;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    public static final String TAG = "MYTAG";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

//该方法会调用 Service 中的 onCreate() 和 onStartCommand() 方法来启动一个后台 Service,
// 当Service 销毁时直接调用 onDestroy() 方法。
    public void startService(View view){
        Intent intent = new Intent(MainActivity.this,MyService.class);
        startService(intent);
    }

    public void stopService(View view){
        Intent intent = new Intent(MainActivity.this,MyService.class);
        stopService(intent);
    }

//通过 bindService() 方法启动 Service,则其生命周期受其绑定对象控制。一个 Service 可以同时绑定            
  到多个对象上,当没有任何对象绑定到 Service 上时,该 Service 会被系统销毁
    public void bindService(View view){
        Intent intent = new Intent(MainActivity.this,MyService.class);
        bindService(intent,con,BIND_AUTO_CREATE);
    }

    public void sayHello(View view){
        if (localService != null){
            String hello = null;
            try {
                hello = localService.sayHello();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "sayHello: " + hello);
        }
    }

    public void sayHelloTo(View view){
        if (localService != null){
            Personal person = null;
            try {
                person = localService.sayHelloTo("张三",true,18);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "sayHelloTo: " + person.getName());
        }
    }


    public void unBindService(View view){
        unbindService(con);
    }

    ILocalService localService;
    private ServiceConnection con = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {  //服务连接时回调
            Log.d(TAG, "onServiceConnected: ");
            localService = ILocalService.Stub.asInterface(iBinder);

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {   //服务解绑成功回调
            Log.d(TAG, "onServiceDisconnected: ");
        }
    };
}

Service有两种使用方式
startService:

生命周期: onCreate → startCommand → onDestroy

Service一旦被启动,在调用者没有调用stopService()的前提下,其生命周期就和调用者的生命周期不再关联。即使调用者被杀掉,Service也可以独立生存。

bindService:

生命周期:onCreate → onBind→onUnBind→ onDestroy
与startService方式不同的是,这种方式,service的生命周期是和调用者关联在一起的,如果调用者进程被终结后,服务便会终止。

应用A的Mysevice.java

package com.example.myeverytest;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyService extends Service {

    public static final String TAG = "MYTAG";

    @Override
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android中的AIDLAndroid Interface Definition Language)是一种用于进程通信的机制,它允许在不同进程中的组件之进行通信AIDL是一个基于接口的编程语言,它定义了一组方法,这些方法可以被其他进程中的组件调用。 AIDL的使用步骤如下: 1.定义AIDL接口:定义接口和方法,并在方法中指定参数和返回值类型。 2.实现AIDL接口:实现AIDL接口中定义的方法。 3.注册AIDL服务:在AndroidManifest.xml文件中注册服务。 4.使用AIDL服务:获取AIDL对象并调用方法。 下面是一个简单的例子,演示如何使用AIDL进行进程通信。 1.定义AIDL接口 ``` interface IMyAidlInterface { void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString); } ``` 2.实现AIDL接口 ``` public class MyAidlService extends Service { private static final String TAG = "MyAidlService"; private IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() { @Override public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { Log.d(TAG, "basicTypes: " + anInt + ", " + aLong + ", " + aBoolean + ", " + aFloat + ", " + aDouble + ", " + aString); } }; @Nullable @Override public IBinder onBind(Intent intent) { return mBinder; } } ``` 3.注册AIDL服务 在AndroidManifest.xml文件中添加以下代码: ``` <service android:name=".MyAidlService" android:exported="true"> <intent-filter> <action android:name="com.example.MyAidlService" /> </intent-filter> </service> ``` 4.使用AIDL服务 ``` public class MainActivity extends AppCompatActivity { private IMyAidlInterface mService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(); intent.setAction("com.example.MyAidlService"); intent.setPackage("com.example"); bindService(intent, mConnection, BIND_AUTO_CREATE); } private ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { mService = IMyAidlInterface.Stub.asInterface(iBinder); try { mService.basicTypes(1, 2L, true, 3.0f, 4.0, "Hello, AIDL!"); } catch (RemoteException e) { e.printStackTrace(); } } @Override public void onServiceDisconnected(ComponentName componentName) { mService = null; } }; } ``` 在上面的代码中,我们首先创建一个Intent对象,指定要绑定的服务的包名和类名。然后调用bindService()方法绑定服务,并在onServiceConnected()方法中获取AIDL对象,调用basicTypes()方法向服务传递参数。最后,在onServiceDisconnected()方法中释放AIDL对象。 以上就是使用AIDL进行进程通信的基本步骤。需要注意的是,在使用AIDL时,必须确保服务已经启动,并且在AndroidManifest.xml文件中注册了服务。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值