【Android】远程服务(Remote Service)的使用

最近做项目碰到了这个,貌似也没在意过,随便写写总结一下。

1,远程启动服务。

A应用定义服务如下:

 <service
            android:name="com.pro.testignore.MyService"
            android:enabled="true"
            android:exported="true"
            android:process=":remote">

            <intent-filter>
                <!-- 为Service组件的intent-filter配置action -->
                <action android:name="com.pro.testignore.MyService"></action>
            </intent-filter>

        </service>

B应用调用远程服务代码如下:

 // 5.0以后的隐式调用方式
        Intent mIntent = new Intent();
        mIntent.setAction("com.pro.testignore.MyService");
        mIntent.setPackage("com.pro.testignore");
        Intent eintent = new Intent(getExplicitIntent(this,mIntent));
        startService(eintent);
public static Intent getExplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);
        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            return null;
        }
        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        ComponentName component = new ComponentName(packageName, className);
        // Create a new intent. Use the old one for extras and such reuse
        Intent explicitIntent = new Intent(implicitIntent);
        // Set the component to be explicit
        explicitIntent.setComponent(component);
        return explicitIntent;
    }

以下理论为转载内容

====================================================================================

1.远程服务简介

  • 什么是远程服务
    远程服务(Remote Service)也被称之为独立进程,它不受其它进程影响,可以为其它应用程序提供调用的接口——实际上就是进程间通信IPC(Inter-Process Communication),Android提供了AIDL(Android Interface Definition Language,接口描述语言)工具来帮助进程间接口的建立。

在Android中,不同的应用属于不同的进程(Process),一个进程不能访问其它进程的存储(可以通过ContentProvider实现,如:通讯录的读取)。

  • 远程服务的适用场景
    一般适用于为其它应用程序提供公共服务的Service,这种Service即为系统常驻的Service(如:天气服务等)。
  • 远程服务的优缺点
  • 优点
    1.远程服务有自己的独立进程,不会受到其它进程的影响;
    2.可以被其它进程复用,提供公共服务;
    3.具有很高的灵活性。
  • 缺点
    相对普通服务,占用系统资源较多,使用AIDL进行IPC也相对麻烦。

更多进程间通讯查阅AIDL资料吧。

猜你喜欢

转载自blog.csdn.net/u011368551/article/details/81463011