上篇博客主要介紹了sharedUserId&&Messenger做爲IPC通訊的用法,接着這篇博客要介紹到的是ContentProvider和Socket的詳細使用方法。
android IPC通訊(上)-sharedUserId&&Messenger
android IPC通訊(下)-AIDL
html
<manifest package="com.android.contentprovider"
xmlns:android="schemas.android.com/apk/res/and…">
<permission android:name="com.android.CONTENTPROVIDER_READPERMISSSION"
android:permissionGroup="android.permission-group.STORAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.android.CONTENTPROVIDER_READPERMISSSION"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<provider
android:authorities="com.android.StudentProvider"
android:name="com.android.contentprovider.StudentProvider"
android:permission="com.android.CONTENTPROVIDER_READPERMISSSION"
android:process=":provider"/>
</application>
</manifest>
複製代碼
public class StudentProvider extends ContentProvider {
public static final String AUTHORITY = "com.android.StudentProvider";
public static final Uri STUDENT_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/student");
public static final Uri GRADE_CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/grade");
public static final int STUDENT_URI_CODE = 0;
public static final int GRADE_URI_CODE = 1;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(AUTHORITY, "student", STUDENT_URI_CODE);
sUriMatcher.addURI(AUTHORITY, "grade", GRADE_URI_CODE);
}
private SQLiteDatabase mDb;
@Override
public boolean onCreate() {
mDb = new DbOpenHelper(getContext()).getWritableDatabase();
return true;
}
@Override
public Cursor query(Uri uri, String[] columns, String selection,
String[] selectionArgs, String sortOrder) {
String table = getTableName(uri);
if (table == null) {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
return mDb.query(table, columns, selection, selectionArgs, null, null, sortOrder, null);
}
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
String table = getTableName(uri);
if (table == null) {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
mDb.insert(table, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return uri;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
String table = getTableName(uri);
if (table == null) {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
int count = mDb.delete(table, selection, selectionArgs);
if (count > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return count;
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
String table = getTableName(uri);
if (table == null) {
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
int row = mDb.update(table, values, selection, selectionArgs);
if (row > 0) {
getContext().getContentResolver().notifyChange(uri, null);
}
return row;
}
private String getTableName(Uri uri) {
String tableName = null;
switch (sUriMatcher.match(uri)) {
case STUDENT_URI_CODE:
tableName = DbOpenHelper.STUDENT_TABLE_NAME;
break;
case GRADE_URI_CODE:
tableName = DbOpenHelper.GRADE_TABLE_NAME;
break;
default:break;
}
return tableName;
}
public class DbOpenHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "student_provider.db";
public static final String STUDENT_TABLE_NAME = "student";
public static final String GRADE_TABLE_NAME = "grade";
public DbOpenHelper(Context context) {
super(context, DB_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.beginTransaction();
String sql;
sql = "create table if not exists "+ STUDENT_TABLE_NAME + " (";
sql += "id integer not null primary key , ";
sql += "name varchar(40) not null default 'unknown', ";
sql += "gender varchar(10) not null default 'male',";
sql += "weight float not null default '60'";
sql += ")";
db.execSQL(sql);
sql = "create table if not exists "+GRADE_TABLE_NAME+ " (";
sql += "id integer not null primary key autoincrement, ";
sql += "chinese float not null default '0', ";
sql += "math float not null default '0', ";
sql += "english float not null default '0'";
sql += ")";
db.execSQL(sql);
db.setTransactionSuccessful();
db.endTransaction();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}複製代碼
public class MainActivity extends BaseActivity implements View.OnClickListener{
Uri studentUri;
Uri gradeUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_mainactivity);
findViewById(R.id.btn_query).setOnClickListener(this);
studentUri = StudentProvider.STUDENT_CONTENT_URI;
gradeUri = StudentProvider.GRADE_CONTENT_URI;
ContentValues studentValues = new ContentValues();
studentValues.put("id", 1);
studentValues.put("name", "zhao");
studentValues.put("gender", "male");
studentValues.put("weight", 68.5);
getContentResolver().insert(studentUri, studentValues);
ContentValues gradeValues = new ContentValues();
gradeValues.put("id", 1);
gradeValues.put("chinese", 90.5);
gradeValues.put("math", 80.5);
gradeValues.put("english", 91.5);
getContentResolver().insert(gradeUri, gradeValues);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_query:
StringBuilder stringBuilder = new StringBuilder();
Cursor cursor= getContentResolver().query(studentUri, null, null, null, null);
stringBuilder.append("STUDENT\n");
while (cursor.moveToNext()){
stringBuilder.append("id:").append(cursor.getString(0)).append("\n");
stringBuilder.append("name:").append(cursor.getString(1)).append("\n");
stringBuilder.append("gender:").append(cursor.getString(2)).append("\n");
stringBuilder.append("weight:").append(cursor.getString(3)).append("\n");
}
cursor.close();
cursor = getContentResolver().query(gradeUri, null, null, null, null);
stringBuilder.append("GRADE\n");
while (cursor.moveToNext()){
stringBuilder.append("id:").append(cursor.getString(0)).append("\n");
stringBuilder.append("chinese:").append(cursor.getString(1)).append("\n");
stringBuilder.append("math:").append(cursor.getString(2)).append("\n");
stringBuilder.append("english:").append(cursor.getString(3)).append("\n");
}
cursor.close();
((TextView)findViewById(R.id.tv_result)).setText(stringBuilder);
break;
}
}
}複製代碼
<manifest package="com.android.socket"
xmlns:android="schemas.android.com/apk/res/and…">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".SocketClient">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".SocketServer"
android:process=":socket"/>
</application>
</manifest>複製代碼
public class SocketServer extends Service{
private boolean mIsServiceDestroyed = false;
@Override
public void onCreate() {
new Thread(new TcpServer()).start();
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
mIsServiceDestroyed = true;
super.onDestroy();
}
private class TcpServer implements Runnable {
@Override
public void run() {
ServerSocket serverSocket;
try {
//監聽8688端口
serverSocket = new ServerSocket(8688);
} catch (IOException e) {
L.e(e);
return;
}
while (!mIsServiceDestroyed) {
try {
// 接受客戶端請求,而且阻塞直到接收到消息
final Socket client = serverSocket.accept();
new Thread() {
@Override
public void run() {
try {
responseClient(client);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void responseClient(Socket client) throws IOException {
// 用於接收客戶端消息
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
// 用於向客戶端發送消息
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true);
while (!mIsServiceDestroyed) {
String str = in.readLine();
if (str == null) {
break;
}
L.i("server has received '" + str +"'");
String message = "server has received your message";
out.println(message);
}
out.close();
in.close();
client.close();
}
}複製代碼
public class SocketClient extends BaseActivity implements OnClickListener{
private Button mSendButton;
private EditText mMessageEditText;
private PrintWriter mPrintWriter;
private Socket mClientSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tcpclient);
mSendButton = (Button) findViewById(R.id.send);
mSendButton.setOnClickListener(this);
mMessageEditText = (EditText) findViewById(R.id.msg);
Intent service = new Intent(this, SocketServer.class);
startService(service);
new Thread() {
@Override
public void run() {
connectTCPServer();
}
}.start();
}
private void connectTCPServer() {
Socket socket = null;
while (socket == null) {
try {
//選擇和服務器相同的端口8688
socket = new Socket("localhost", 8688);
mClientSocket = socket;
mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
} catch (IOException e) {
SystemClock.sleep(1000);
}
}
try {
// 接收服務器端的消息
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (!isFinishing()) {
String msg = br.readLine();
if (msg != null) {
String time = formatDateTime(System.currentTimeMillis());
L.i("client has received '" + msg + "' at " + time);
}
}
mPrintWriter.close();
br.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
if (mClientSocket != null) {
try {
mClientSocket.shutdownInput();
mClientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
@Override
public void onClick(View v) {
if (v == mSendButton) {
final String msg = mMessageEditText.getText().toString();
if (!TextUtils.isEmpty(msg) && mPrintWriter != null) {
//像服務器發送信息
L.i("client has send '" + msg + "' at " + formatDateTime(System.currentTimeMillis()));
mPrintWriter.println(msg);
mMessageEditText.setText("");
}
}
}
private String formatDateTime(long time) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time));
}複製代碼
com.android.socket I/[PID:20730]: [TID:1] SocketClient.onClick(line:99): client has send 'hello i am client' at 2015-12-14 15:59:18
com.android.socket:socket I/[PID:20784]: [TID:5918] SocketServer.responseClient(line:90): server has received 'hello i am client'
com.android.socket I/[PID:20730]: [TID:5902] SocketClient.connectTCPServer(line:69): client has received 'server has received your message' at 2015-12-14 15:59:18複製代碼
經過日誌能夠清楚地看到SocketServer是在20784進程中,SocketClient是在20730進程中,很明顯的跨進程之間的通訊。
固然Socket除了使用TCP套接字以外,還可以使用UDP套接字。另外經過Socket不只僅可以實現進程之間的通訊,還能夠實現設備間的通訊,前提是這些設備之間的IP地址互相可見,若是須要繼續深刻能夠去查閱相關的資料,在這就不介紹了。
源碼下載:github.com/zhaozepeng/…java