24 AIDL案例

服务端

这里写图片描述

MainActivity.java

package com.qf.day24_aidl_wordserver;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MainActivity extends Activity {

    private EditText etEn,etCh;
    private ListView lv;

    private MyOpenDbHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化View
        initView();
        helper = new MyOpenDbHelper(getApplicationContext());

        getData();
    }

    public void initView() {
        etEn = (EditText) findViewById(R.id.et_en);
        etCh = (EditText) findViewById(R.id.et_ch);
        lv = (ListView) findViewById(R.id.lv);
    }

    //点击进行保存
    public void saveClick(View v){

        String etEnStr = etEn.getText().toString().trim();
        String etChStr = etCh.getText().toString().trim();

        String sql = "insert into tb_words(word,detail) values(?,?)";
        //添加数据到数据库
        helper.execSqlData(sql, new String[]{etEnStr,etChStr});

        getData();
    }

    //查询数据展示到LIstVIew
    public void getData(){

        String sql = "select * from tb_words";
        Cursor cursor = helper.queryData(sql, null);

        SimpleCursorAdapter adapter = new SimpleCursorAdapter
                (MainActivity.this, 
                        R.layout.item, 
                        cursor, 
                        new String[]{"word","detail"},
                        new int[]{R.id.tv_en,R.id.tv_ch},
                        SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

        lv.setAdapter(adapter);
    }



}

MyOpenDbHelper.java

package com.qf.day24_aidl_wordserver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class MyOpenDbHelper extends SQLiteOpenHelper{

    private static final String NAME ="db_words.db";
    private static final int VERSION =1;


    private SQLiteDatabase db ;
    public MyOpenDbHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }
    public MyOpenDbHelper(Context context) {
        super(context, NAME, null, VERSION);
        // TODO Auto-generated constructor stub
        db = getReadableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        String sql ="create table if not exists tb_words(_id integer primary key autoincrement,word,detail)";
        db.execSQL(sql);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

    //查询
    public Cursor queryData(String sql, String[] selectionArgs){
        return db.rawQuery(sql, selectionArgs);
    }


    // 增 删改
    public boolean execSqlData(String sql, Object[] bindArgs){
        try {
            if(bindArgs!=null){

                db.execSQL(sql, bindArgs);
            }else{
                db.execSQL(sql);
            }

            return true;

        } catch (Exception e) {
            // TODO: handle exception
            return false;
        }

    }

    //查询所有数据  返回List<>
    public List<Map<String,Object>> selectData(String sql, String[] selectionArgs){

        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        Cursor cusor = db.rawQuery(sql, selectionArgs);

        while(cusor.moveToNext()){
            Map<String,Object> map = new HashMap<String, Object>();
            for(int i=0;i<cusor.getColumnCount();i++){
                map.put(cusor.getColumnName(i), cusor.getString(i));
            }
            list.add(map);
        }
        return list;

    }
}

MyService.java

package com.qf.day24_aidl_wordserver;

import java.util.List;
import java.util.Map;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import com.qf.day24_aidl_wordserver.MyInterfaceWord.Stub;

public class MyService extends Service{

    private MyOpenDbHelper helper;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return new MyBinder();
    }

    class MyBinder extends Stub{

        @Override
        public String getValues(String word) throws RemoteException {
            // TODO Auto-generated method stub
            String sql = "select * from tb_words where word = ?";
            List<Map<String, Object>> list = helper.selectData(sql, new String[]{word});
            return list.toString();
        }

    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        helper = new MyOpenDbHelper(getApplicationContext());
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // TODO Auto-generated method stub
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

}

MyInterfaceWord.aidl

package com.qf.day24_aidl_wordserver;

 interface MyInterfaceWord {
    String getValues(String word);
}

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.qf.day24_aidl_wordserver"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.qf.day24_aidl_wordserver.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService">
            <intent-filter >
                <action android:name="com.qf.day24_aidl_wordserver.MyService"/>
            </intent-filter>
        </service>
    </application>

</manifest>

布局文件
这里写图片描述

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_en"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入英文..." />
    <EditText
        android:id="@+id/et_ch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入中文..." />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="saveClick"
        android:text="保存"
        />
    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00ff00"
        android:text="以下展示内容"
        />
    <ListView
        android:id="@+id/lv" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></ListView>

</LinearLayout>

item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView 
        android:id="@+id/tv_en"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tv"
        android:textColor="#f00"
        />
    <TextView 
        android:id="@+id/tv_ch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tv"
        android:textColor="#00f"
        />


</LinearLayout>

客户端

这里写图片描述

MainActivity.java

package com.qf.day24_aidl_wordclient;

import com.qf.day24_aidl_wordserver.MyInterfaceWord;
import com.qf.day24_aidl_wordserver.MyInterfaceWord.Stub;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private EditText etWord;
    private TextView tvShow;

    private MyInterfaceWord myInterfaceWord;

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

        etWord = (EditText) findViewById(R.id.et_word);
        tvShow = (TextView) findViewById(R.id.tv_show);

        ServiceConnection conn = new ServiceConnection() {

            @Override
            public void onServiceDisconnected(ComponentName name) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // TODO Auto-generated method stub
                myInterfaceWord = Stub.asInterface(service);
            }
        };

        Intent intent = new Intent("com.qf.day24_aidl_wordserver.MyService");
        //6.0必须加上
        intent.setPackage("com.qf.day24_aidl_wordserver");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);


    }


    public void MyClick(View v){

        try {
            String str = myInterfaceWord.getValues(etWord.getText().toString().trim());

            tvShow.setText(str);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}

MyInterfaceWord .java

package com.qf.day24_aidl_wordserver;

 interface MyInterfaceWord {
    String getValues(String word);
}

AndroidManifest.xml 清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.qf.day24_aidl_wordclient"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.qf.day24_aidl_wordclient.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/et_word"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入查询内容" />

    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查询"
        android:onClick="MyClick"
        />

    <TextView
        android:id="@+id/tv_show" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        />
</LinearLayout>
原文地址:https://www.cnblogs.com/muyuge/p/6152180.html