个人日记~多个Activity与同一线程通讯

  • Post author:
  • Post category:其他


个人日记~多个Activity与同一线程通讯

Socket在使用时只能有一个连接存在,多个Activity都需要使用同一个连接,要处理一下消息的传递。

示例步骤 复制不能运行

一.使用LocalBroadcastManager 本地广播

  1. mainActivity中启动Socket 注册本地广播
    public static Socket socket;
    //图省事 直接全局socket
    private BufferedReader in;
    private OutputStreamWriter out;

    private IntentFilter mIntentFilter;
    private LocalReceiver mLocalReceiver;
    private LocalBroadcastManager mLocalBroadcastManager;
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SocketINIT();
        soketRec();
        //监听readLine()
        
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
       //注册本地广播监听器
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction("mSocketTest");
        mLocalReceiver = new LocalReceiver();
        mLocalBroadcastManager.registerReceiver(mLocalReceiver, mIntentFilter);

2.处理广播数据,重写BroadcastReceiver

        static class LocalReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getExtras().getString("SocketData");
                //数据处理
                Toast.makeText(context, action, Toast.LENGTH_SHORT).show();
            }
        }
        @Override
        protected void onDestroy () {
            super.onDestroy();
            //销毁广播
            mLocalBroadcastManager.unregisterReceiver(mLocalReceiver);
        }

3.Socket连接 监听 发送广播

     public void SocketINIT () {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        socket = new Socket("www.test.net", 8585);
                        iswork = true;
                    } catch (IOException | e) {
                        e.printStackTrace();
                    }
                }
            }).start();
         }
        }

       public void soketRec () {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        while (iswork) {
                            String Tmp = in.readLine();
                            //Socket接收到的数据
                            Intent sendIntent = new Intent("mSocketTest");
                            sendIntent.putExtra("SocketData", Tmp);
                            mLocalBroadcastManager.sendBroadcast(sendIntent);
                            //发送广播
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

4.其他的Activity只需注册广播为(“mSocketTest”),

       public class MainActivity2 extends AppCompatActivity {
       @Override
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
       //注册MainActivity2本地广播监听器
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction("mSocketTest");
        MainActivity.LocalReceiver mLocalReceiver = new MainActivity.LocalReceiver();
        //test直接用MainActivity的LocalReceiver(),使用应该重写BroadcastReceiver
        mLocalBroadcastManager.registerReceiver(mLocalReceiver, mIntentFilter);
          }
        }


分割线

=================================

二.使用Handler 这个简单一些

1.实现MAIN_Handler

    public static Socket socket;
    //图省事 直接全局socket
    private BufferedReader in;
    private OutputStreamWriter out;
    
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SocketINIT();
        SetHandler(MAIN_Handler);//绑定MAIN_Handler
        soketRec();
        //监听readLine()
  }

    protected void onResume() {
        super.onResume();
        Log.i("onResume","main_onResume");
        SetHandler(MAIN_Handler);
        //重新加载Activity,重新绑定Handler
    }


    private Handler MAIN_Handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == 200) {
                    //收到soketRec ()线程消息后,数据处理
                    Toast.makeText(context, (String) msg.obj, Toast.LENGTH_SHORT).show();
                }
            }
        };//接受处理自定义消息(处理UI线程任务)

2.Socket连接 监听 发送广播

public void SetHandler(Handler RecHandler) {
        mHandler=RecHandler;
    }
//绑定你需要的Activity主线程消息Handler

public void soketRec () {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        while (iswork) {
                            msg = mHandler.obtainMessage();
                            msg.obj = in.readLine();
                            //Socket接收到的数据
                            msg.arg1 = 1;
                            msg.what = 200;
                            mHandler.sendMessage(msg);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

3.其他的Activity只需 SetHandler(你需要的Activity主线程Handler)

 public class MainActivity2 extends AppCompatActivity {
       @Override
       protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        SetHandler(MAIN2_Handler);//绑定MAIN2_Handler
        



版权声明:本文为kk1271原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。