Android IPC之ContentProvider和Socket(Android开发艺术探索随笔)

ContentProvider作为Android4大组件之一,本就是用来实现不同应用之间数据共享。那么肯定可以实现进程间通信。ContentProvider的底层也是同Binder实现的。
记录下书中的例子。
首先是一个DbOpenHeper,负责数据 库的创建和升级,代码如下

public class DbOpenHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "book_provider.db";

    public static final String BOOK_TABLE_NAME = "book";
    public static final String USER_TABLE_NAME = "user";

    private static final int DB_VERSION = 1;

    private String CREATE_BOOK_TABLE = "CREATE TABLE IF NOT EXISTS "
                                        +BOOK_TABLE_NAME
                                        + "(_id INTEGER PRIMARY KEY,"
                                        +"name TEXT)";
    private String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS "
                                        +USER_TABLE_NAME
                                        + "(_id INTEGER PRIMARY KEY,"
                                        +"name TEXT," + "sex INT)";



    public DbOpenHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK_TABLE);
        db.execSQL(CREATE_USER_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

其次是一个provider类,负责数据的CURD等等。在ContentProvider中,要关联URI和table。使用如下代码关联Uri和code

private static final String AUTHORITY = "com.gl.provider.book.provider";
    private static final int BOOK_URI_CODE = 0;
    private static final int USER_URI_CODE = 1;

    private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);

    static{
        matcher.addURI(AUTHORITY,"book",BOOK_URI_CODE);
        matcher.addURI(AUTHORITY,"user",USER_URI_CODE);
    }

query的代码

@Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // TODO: Implement this to handle query requests from clients.
        Log.d("tag","query current thread:"+Thread.currentThread().getName());

        String table = getTableName(uri);
        return mDb.query(table,projection,selection,selectionArgs,null,null,sortOrder,null);
    }

上面的mDb就是openHelper。
将这个Provider通过progress属性开启其他进程。并声明

android:authorities="com.gl.provider.book.provider"

接下来我们看,如何调用。

resolver = getContentResolver();
Uri bookUri = Uri.parse("content://com.gl.provider.book.provider/book");
                ContentValues values= new ContentValues();
                values.put("_id", 6);
                values.put("name", "Android 开发艺术探索");
                resolver.insert(bookUri, values);
                Cursor cursor = resolver.query(bookUri,new String[]{"_id","name"},null,null,null);
                while (cursor.moveToNext()){
                    Book book = new Book();
                    book.bookId = cursor.getInt(0);
                    book.bookName = cursor.getString(1);
                    Log.w("tag","query book:"+book.toString());
                }
                cursor.close();

恩,其实很简单。这只是contentprovider的一些基础用法。想了解更多用法请查看官方文档或者百度其他博客。

Socket被成为“套接字”,是网络通信中的概念,它分为流式套接字和用户数据套接字两种,分别对应TCP和UDP协议。
以书上的例子来记录下如何通过socket来进行进程间通信。

首先是服务端。在Service的onCreate方法中开启一个线程去等待客户端的输入。下面只给出关键代码。
首先,new一个ServerSocket去监听客户端端口

serverSocket = new ServerSocket(8688);

接着接受客户端的socket

final Socket client = serverSocket.accept();

然后去回复一条消息。

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        //用于向客户端发送消息
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())),true);
        out.println("欢迎来到聊天室");
        out.flush();

看看客户端是怎么实现的。

//向服务端发送消息
socket = new Socket("localhost",8688);
                mClientSocket = socket;
                mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                mPrintWriter.println("hello server");
                mPrintWriter.flush();
//接受服务端消息
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (!MainActivity.this.isFinishing()){
                    String msg = br.readLine();
                    Log.e("tag","receive:"+msg);

                }

socket的简单用法 就是这么简单。但是socket有很多复杂的用法等待着我们去学习。

代码地址:github

你可能感兴趣的:(android,socket,ipc)