Android使用文件进行IPC
程序员文章站
2024-02-22 17:07:10
一、文件进行ipc介绍
共享文件也是一种不错的进程间通信方式,两个进程通过读/写同一个文件来交换数据。在windows上,一个文件如果被加了排斥锁将会导致其他线程无法对其...
一、文件进行ipc介绍
共享文件也是一种不错的进程间通信方式,两个进程通过读/写同一个文件来交换数据。在windows上,一个文件如果被加了排斥锁将会导致其他线程无法对其进行访问,包括读写,而由于android系统基于linux,使其并发读/写文件可以没有限制地进行,甚至两个线程同时对同一个文件进行读写操作是允许的,尽管这可能出现问题。通过文件交换数据很好使用,除了可以交换一些文本信息外,还可以序列化一个对象到文件系统中的同时从另一个进程中恢复这个对象。
二、使用方法
1.数据类实现parcelable或serializable接口
public class user implements parcelable, serializable { public user() { } public user(int userid, string username, boolean ismale) { ... } @override public int describecontents() { return 0; } @override public void writetoparcel(parcel dest, int flags) { ... } public static final parcelable.creator<user> creator = new parcelable.creator<user>() { @override public user createfromparcel(parcel source) { return ...; } @override public user[] newarray(int size) { return ...; } }; private user(parcel in) { ... } @override public string tostring() { return ...; } }
2.序列化一个对象到sd卡上的一个文件里
private void persisttofile() { new thread(new runnable() { @override public void run() { user user = new user(1, "hello world", false); file dir = new file(myconstants.chapter_2_path); if (!dir.exists()) { dir.mkdirs(); } file cachedfile = new file(myconstants.cache_file_path); objectoutputstream objectoutputstream = null; try { objectoutputstream = new objectoutputstream(new fileoutputstream(cachedfile)); objectoutputstream.writeobject(user); log.d(tag, "persist user:" + user); mtextview.settext("persist user:" + user); } catch (ioexception e) { e.printstacktrace(); } finally { myutils.close(objectoutputstream); } } }).start(); }
3.在另外的进程中反序列化
private void recoverfromfile(){ new thread(new runnable() { @override public void run() { user user = null; file cachedfile = new file(myconstants.cache_file_path); if(cachedfile.exists()){ objectinputstream objectinputstream = null; try{ objectinputstream = new objectinputstream(new fileinputstream(cachedfile)); user = (user)objectinputstream.readobject(); log.d(tag,"recover user:"+user); mtextview.settext("recover user:"+user); }catch (ioexception e) { e.printstacktrace(); }catch (classnotfoundexception e){ e.printstacktrace(); }finally { myutils.close(objectinputstream); } } } }).start(); }
4.在androidmanifest.xml中开启多进程
<activity ... android:process=":remote" />
三、小案例
1.修改activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?> <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:fitssystemwindows="true" tools:context="com.zhangmiao.ipcdemo.mainactivity" android:orientation="vertical" > <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="file"> </textview> <button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="open activity b" /> <textview android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="a"> </textview> </linearlayout>
2.添加activity_second.xml文件
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="at activity b" android:layout_gravity="center_horizontal" /> <textview android:id="@+id/textview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="activity b" /> </linearlayout>
3.添加myutils类与myconstants类(辅助类)
package com.zhangmiao.ipcdemo; import android.app.activitymanager; import android.content.context; import java.io.closeable; import java.io.ioexception; import java.util.list; import java.util.concurrent.recursivetask; /** * created by zhangmiao on 2016/12/26. */ public class myutils { public static void close(closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (ioexception e) { e.printstacktrace(); } } }
package com.zhangmiao.ipcdemo; import android.os.environment; /** * created by zhangmiao on 2016/12/26. */ public class myconstants { public static final string chapter_2_path = environment.getexternalstoragedirectory().getpath() + "/zhangmiao/charpter_2/"; public static final string cache_file_path = chapter_2_path + "usercache"; public static final int msg_from_client = 0; public static final int msg_from_service = 1; }
4.添加user类
package com.zhangmiao.ipcdemo; import android.os.parcel; import android.os.parcelable; import java.io.serializable; /** * created by zhangmiao on 2016/12/26. */ public class user implements parcelable, serializable { public static int suserid = 1; private int userid; private string username; private boolean ismale; public user() { } public user(int userid, string username, boolean ismale) { this.userid = userid; this.username = username; this.ismale = ismale; } @override public int describecontents() { return 0; } @override public void writetoparcel(parcel dest, int flags) { dest.writeint(userid); dest.writestring(username); dest.writeint(ismale ? 1 : 0); } public static final parcelable.creator<user> creator = new parcelable.creator<user>() { @override public user createfromparcel(parcel source) { return new user(source); } @override public user[] newarray(int size) { return new user[size]; } }; private user(parcel in) { userid = in.readint(); username = in.readstring(); ismale = in.readint() == 1; } @override public string tostring() { return string.format( "user:{userid:%s, username:%s, ismale:%s},",userid, username, ismale ); } }
5.添加secondactivity类
package com.zhangmiao.ipcdemo; import android.app.activity; import android.os.bundle; import android.util.log; import android.widget.textview; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.objectinputstream; /** * created by zhangmiao on 2016/12/26. */ public class secondactivity extends activity { private static final string tag = "secondactivity"; private textview mtextview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_second); log.d(tag, "oncreate"); mtextview = (textview)findviewbyid(r.id.textview1); } @override protected void onresume() { log.d(tag,"onresume"); super.onresume(); user user = (user)getintent().getserializableextra("extra_user"); log.d(tag,"user:"+user.tostring()); recoverfromfile(); } private void recoverfromfile(){ new thread(new runnable() { @override public void run() { user user = null; file cachedfile = new file(myconstants.cache_file_path); if(cachedfile.exists()){ objectinputstream objectinputstream = null; try{ objectinputstream = new objectinputstream(new fileinputstream(cachedfile)); user = (user)objectinputstream.readobject(); log.d(tag,"recover user:"+user); mtextview.settext("recover user:"+user); }catch (ioexception e) { e.printstacktrace(); }catch (classnotfoundexception e){ e.printstacktrace(); }finally { myutils.close(objectinputstream); } } } }).start(); } }
6.修改mainactivity类
package com.zhangmiao.ipcdemo; import android.content.componentname; import android.content.context; import android.content.intent; import android.content.serviceconnection; import android.os.bundle; import android.os.handler; import android.os.ibinder; import android.os.message; import android.os.messenger; import android.os.remoteexception; import android.support.v7.app.appcompatactivity; import android.util.log; import android.view.view; import android.widget.button; import android.widget.textview; import java.io.file; import java.io.fileoutputstream; import java.io.ioexception; import java.io.objectoutputstream; import java.io.serializable; public class mainactivity extends appcompatactivity { private static final string tag = "mainactivity"; private textview mtextview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); user.suserid = 2; findviewbyid(r.id.button1).setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { intent intent = new intent(); intent.setclass(mainactivity.this, secondactivity.class); user user = new user(0, "jake", true); intent.putextra("extra_user", (serializable) user); startactivity(intent); } }); mtextview = (textview) findviewbyid(r.id.textview1); } @override protected void onresume() { super.onresume(); log.d(tag, "usermanager.suserid=" + user.suserid); super.onstart(); persisttofile(); } private void persisttofile() { new thread(new runnable() { @override public void run() { user user = new user(1, "hello world", false); file dir = new file(myconstants.chapter_2_path); if (!dir.exists()) { dir.mkdirs(); } file cachedfile = new file(myconstants.cache_file_path); objectoutputstream objectoutputstream = null; try { objectoutputstream = new objectoutputstream(new fileoutputstream(cachedfile)); objectoutputstream.writeobject(user); log.d(tag, "persist user:" + user); mtextview.settext("persist user:" + user); } catch (ioexception e) { e.printstacktrace(); } finally { myutils.close(objectoutputstream); } } }).start(); } }
7.修改androidmanifest.xml文件
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.zhangmiao.ipcdemo"> <uses-permission android:name="android.permission.write_external_storage" /> <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" android:label="@string/app_name" android:launchmode="standard" android:theme="@style/apptheme.noactionbar"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <activity android:name=".secondactivity" android:configchanges="screenlayout" android:label="@string/app_name" android:process=":remote" /> </application> </manifest>
完整代码下载地址:https://github.com/zhangmiao147/ipcdemo
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读
-
Android使用文件进行IPC
-
Android之使用Bundle进行IPC详解
-
Android中使用SDcard读取文件
-
Android使用缓存机制实现文件下载及异步请求图片加三级缓存
-
gradlew wrapper使用下载到本地的gradle.zip文件安装。 博客分类: java基础android
-
gradlew wrapper使用下载到本地的gradle.zip文件安装。 博客分类: java基础android
-
Android使用KeyStore对数据进行加密的示例代码
-
Android 使用版本控制工具时添加忽略文件的方式(详解)
-
使用socket进行服务端与客户端传文件的方法
-
Android编程之include文件的使用方法