android AIDL 实践之传递简单字串

*本demo的server和client写反了

新建工程client,server

在server端新建aidl文件,内容:

// IMyAidlInterface.aidl
package com.example.server;

// Declare any non-default types here with import statements

interface IMyAidlInterface {

    String getString();
}

Make project自动在server\build\generated\source\aidl\debug\com\example\server生成java类

在client新建同样文件,同样生成java类

*注意两个的包名要一致

在server编写service服务

package com.example.client;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.server.IMyAidlInterface;

/**
 * Created by luozhenlonghp on 2017/5/13.
 */

public class Myservice extends Service {
    public static final String TAG = "Myservice";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return result;
    }

    IMyAidlInterface.Stub result = new IMyAidlInterface.Stub(){

        @Override
        public String getString() throws RemoteException {
            return "you get it";
        }
    };

    @Override
    public void onCreate() {
        Log.i(TAG,"onCreate is called");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG,"onStartCommand is called");
        return super.onStartCommand(intent, flags, startId);
    }
}

 

在menifest文件中注册

<service android:name=".Myservice" 
 
//这里表示进程名
android:process="com.test.myservice">

    <intent-filter>
        <action android:name="android.intent.action.RESPOND_VIA_MESSAGE"></action>
    </intent-filter>
</service>

 

在client端写代码绑定service

public void bindMyservice()
{
    Intent intent = new Intent();
    //这里是action
intent.setAction("android.intent.action.RESPOND_VIA_MESSAGE");
//这里是服务端的包名,本次demo写反了
    intent.setPackage("com.example.client");
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//这里获得实例
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);

            try {
                String result = iMyAidlInterface.getString();
                Toast.makeText(MainActivity.this,result , Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            }


        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    bindService(intent,connection,BIND_AUTO_CREATE);
}

大功告成

转载于:https://www.cnblogs.com/dp-luo/p/6848477.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值