淘先锋技术网

首页 1 2 3 4 5 6 7

首先,先看一下Services端目录结构:


先在src目录下创建一个文件,命名为Count.aidl 此时在gen目录下就会自动创建一个Count.java文件,把这个文件复制到Client项目的src文件下即可。

Service短的代码如下:

public class MyServer extends Service {

  class Mylocation extends Count.Stub{
        @Override
        public double count(double a, double b) throws RemoteException {
            return a+b;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        return new Mylocation();
    }
    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
}
此时要在AndroidManifest.xml中注册:

 <service android:name="com.zhongyan.server.MyServer" android:process=":remote" android:exported="true" >
            <intent-filter>
                <action android:name="com.zhongyan.server.bindServer"/>
            </intent-filter>
  </service>

切记跨进程通信一定要加这个属性 android:exported="true" ,该属性用来标示,其它应用的组件是否可以唤醒service或者和这个service进行交互:true可以,false不可以。如果为false,只有同一个应用的组件或者有着同样user ID的应用可以启动这个service或者绑定这个service。

Client端代码如下:

public class MainActivity extends Activity {
    private Button btnCalculate;
    private EditText etNum1;
    private EditText etNum2;
    private TextView tvResult;
    private Count mcount;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etNum1 = (EditText) findViewById(R.id.et_num_one);
        etNum2 = (EditText) findViewById(R.id.et_num_two);

        tvResult = (TextView) findViewById(R.id.tv_result);
        btnCalculate = (Button) findViewById(R.id.btn_cal);

        Intent intent = new Intent();
        intent.setAction("com.zhongyan.server.bindServer");
        intent.setPackage("com.zhongyan.serveraidl");
        bindService(intent,connection,Context.BIND_AUTO_CREATE);
        btnCalculate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                try {
                    double num1 = Double.parseDouble(etNum1.getText().toString());
                    double num2 = Double.parseDouble(etNum2.getText().toString());
                    String result;
                    if (mcount!= null){
                        result = "计算结果:"+ mcount.count(num1, num2);
                        tvResult.setText(result);
                    }

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mcount = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mcount = Count.Stub.asInterface(service);
        }
    };
}
Client的界面显示如下:


如果连接成功,输入数字,点击计算就可以看到结果了。