Android--多个Activity共享Socket--单例模式
生活随笔
收集整理的這篇文章主要介紹了
Android--多个Activity共享Socket--单例模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
自己跟同學校能電院同學一起做的創新訓練項目:
樹莓派端與app端建立Socket通信,要求app端收發信息,樹莓派端處理信息。
問題:在多個Activity之間共享Socket通信,使用設計模式單例模式:單例模式保證在程序中只有一個實例存在并且能全局的訪問到。
public class MSocket extends Socket{//private static final String host="192.168.31.16";private static final String host="192.168.43.110";private static final int port=12345;private static BufferedReader br = null;private static PrintWriter pw = null;/*?持有私有靜態實例,防止被引用,此處賦值為null,目的是實現延遲加載?*/private static MSocket socket=null;private MSocket(String host, int port) throws UnknownHostException, IOException {super(host, port);}public static MSocket getsocket() throws IOException {if(socket==null){socket= new MSocket(host,port);}return socket;}public static BufferedReader getbr() throws IOException {if(br==null){br=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));}return br;}public static PrintWriter getpw() throws IOException {if(pw==null){pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);}return pw;}--------------------- 作者:lhp15575865420 來源:CSDN 原文:https://blog.csdn.net/lhp15575865420/article/details/75136649 版權聲明:本文為博主原創文章,轉載請附上博文鏈接!博主的這篇文章真的讓我又學習了不少知識。
用static關鍵字保證socket被所有的對象所共享,內存中只有一個副本。所以可以實現共享!
總結
以上是生活随笔為你收集整理的Android--多个Activity共享Socket--单例模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 洛谷——P1059 明明的随机数
- 下一篇: Android总结 之 AsyncTas