Socket传递数据,ListView展示数据

来源:互联网 发布:mysql数据库没有了 编辑:程序博客网 时间:2024/06/06 16:21
一个简单的Socket传递数据,并存储在SQLite通过ListView展示数据的APP;

public class MainActivity extends AppCompatActivity implements RFIDInfoInterface {
    private TextView itemcontent;
    private WifiReceiver wifiReceiver;
    private TextView onoff;
    private TextView name;
    private ListView listView;
    private List<CardInfo> cardInfos = new ArrayList<>();

    private Button Warehousing; //入库
    private Button Outhousing;//出库
    private Button ShowInventory;//显示库存
    private MyOpenHelper openHelper;
    private MainServer server;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String content = null;
            if (msg.what == 1) {
                if (msg.obj != null) {
                    content = msg.obj.toString();
                    itemcontent.setText(content);//将获取到的数据显示在下方显示框中,并且更新UI需要在子线程中去执行
                } else {
                    //不做处理
                }
            }
        }
    };

    private Runnable queryRunnable = new Runnable() {
        @Override
        public void run() {
            query();//当打开时就查询数据库的内容并显示在ListView
        }
    };
    private String cardInfo1 = null;

    @Override
    public void getInfo(String info) {
        Log.d("回调函数", "info--->" + info);
        cardInfo1 = info;
        Message msg = handler.obtainMessage();
        msg.what = 1;
        msg.obj = cardInfo1;
        handler.sendMessage(msg);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        server.receiveData(); //开启服务器接收数据
        server.setObj(MainActivity.this);

        handler.post(queryRunnable);//通过Handler启动线程查询数据库
        listView.setAdapter(new MyAdapter());//为listView设置适配器
        //为ListView条目添加长按删除的效果
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final int index = position;//确认在数据中的位置
                final View par = view;
                Log.d("index", "index-->" + index);
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("确认删除吗?");
                builder.setTitle("提示");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        TextView textView = (TextView) par.findViewById(R.id.CardStyle); //你的xml布局文件中要获取的textview
                        String str = (String) textView.getText();
                        System.out.println("str--->" + str);
                        outHousing(str, index);//根据卡类型删除
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
                return true;
            }
        });
    }

    /**
     * 初始化组件信息
     */
    public void init() {
        server = new MainServer();
        Warehousing = (Button) findViewById(R.id.Warehousing);//入库
        Outhousing = (Button) findViewById(R.id.Outhousing);    //出库
        ShowInventory = (Button) findViewById(R.id.ShowInventory);//显示库存

        onoff = (TextView) findViewById(R.id.onoff);//wifi的状态,打开或者关闭
        name = (TextView) findViewById(R.id.name);  //连接到的wifi名称
        listView = (ListView) findViewById(R.id.listView);//显示数据库中所有的信息
        itemcontent = (TextView) findViewById(R.id.itemcontent);//单个录入时显示卡的信息
        openHelper = new MyOpenHelper(MainActivity.this);

        wifiReceiver = new WifiReceiver();  //广播接收器动态注册
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);//添加Action
        registerReceiver(wifiReceiver, filter);
    }


    /**
     * APP退出时
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Main onDestory", "注销广播");
        unregisterReceiver(wifiReceiver);
        //程序退出停止线程
        handler.removeCallbacks(queryRunnable);
        //应用退出时关闭服务
//        if (server!=null) {
//            server.closeServer();
//        }
    }

    /**
     * @param view 入库操作
     */
    public void wareHousing(View view) {
        Log.d("ServerClass", "入库");
        final SQLiteDatabase database = openHelper.getReadableDatabase();
        //执行一个对话框,然后点击确认后,执行入库操作,这块应该是获取服务器接收到的数据,即将服务器接收到的数据传到此处。
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("提示");
        builder.setMessage("确认数据?");
//        builder.setMessage(new TextView(MainActivity.this).setText());
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                //cardInfo.split();用该方法可以将字符串分离开来,并分别赋值给style  model
                Log.d("插入----", "cardInfo1-->" + cardInfo1);
                //这里需要对传入的卡的信息进行处理,比如字符串分割,
                if (!TextUtils.isEmpty(cardInfo1)) {
                    String style = cardInfo1;      //卡类型
                    String model = cardInfo1;      //卡型号
//                itemcontent.setText("卡类型:" + style + "\n" + "卡型号:" + model);//测试使用可以注释掉
                    ContentValues values = new ContentValues();
                    values.put("rfidcardstyle", style);
                    values.put("rfidcardmodel", model);
                    long insert = database.insert("rfidcardinfo", null, values);//返回的数据大于0说明插入成功了
                    if (insert > 0) {
                        //创建一个类的对象,将model值、style值传给该对象,进行数据更新。
                        CardInfo cardInfo = new CardInfo();
                        cardInfo.cardModel = model;
                        cardInfo.cardStyle = style;
                        cardInfos.add(0, cardInfo);
                        Toast.makeText(getApplicationContext(), "插入成功", Toast.LENGTH_LONG).show();
                        cardInfo1 = null;
                        itemcontent.setText(" ");
                    } else {
                        Toast.makeText(getApplicationContext(), "插入失败", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "未扫描到信息", Toast.LENGTH_LONG).show();
                }
                database.close();
                dialog.dismiss();
                new MyAdapter().notifyDataSetChanged();
                listView.setAdapter(new MyAdapter());
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     * 删除操作
     */
    public void outHousing(final String str, final int index) {
        Log.d("ServerClass", "出库");
        SQLiteDatabase database = openHelper.getReadableDatabase();
        // 删除表的所有数据
        // db.delete("users",null,null);
        // 从表中删除指定的一条数据,根据卡的类型删除
        String style = "rfidcardstyle";
        String[] whereArgs = {str};
        database.delete("rfidcardinfo", style + "=?", whereArgs);//执行删除程序
        cardInfos.remove(index);//从listView中删除
        database.close();//关闭数据库
        new MyAdapter().notifyDataSetChanged();//更新数据
        listView.setAdapter(new MyAdapter());//重新设置Adapter
    }

    /**
     * @param view 显示所有库存
     */
    public void showInventory(View view) {
        Log.d("ServerClass", "显示库存");
        //查询的耗时操作要在子线程中操作,如果数据量大的话会造成Activity异常
        handler.post(queryRunnable);
    }


    private void query() {
        SQLiteDatabase database = openHelper.getReadableDatabase();
        String query = "select * from rfidcardinfo";    //从表中插叙全部的数据
        Cursor cursor = database.rawQuery(query, null);
        Log.d("MainActivity", "cursor--->" + cursor.getCount());
        //将数据库的数据显示在ListView中
        cardInfos.clear();
        CardInfo info = null;
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                info = new CardInfo();
                info.cardModel = cursor.getString(2);
                info.cardStyle = cursor.getString(1);
                cardInfos.add(0, info);
                String id = cursor.getString(0);
                System.out.println("id---->" + id);
            }
            listView.setAdapter(new MyAdapter());//为listView设置适配器
        }
    }

    /**
     * @return 获取当期那连接的wifi的名字
     */
    private String getConnectWifiSsid() {
        WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        Log.d("wifiInfo-->", wifiInfo.toString());
        Log.d("SSID-->", wifiInfo.getSSID());
        return wifiInfo.getSSID();
    }


    /**
     * 监听wifi的广播
     */
    public class WifiReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)) {
                //获取当前的wifi状态int类型数据
                int mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (mWifiState) {
                    case WifiManager.WIFI_STATE_ENABLED:
                        //已打开
                        String wifiName = getConnectWifiSsid();
                        System.out.println("打开");
                        onoff.setText("打开");
                        name.setText(wifiName);
                        break;
                    case WifiManager.WIFI_STATE_DISABLED:
                        //已关闭
                        System.out.println("关闭");
                        onoff.setText("关闭");
                        break;

                    case WifiManager.WIFI_STATE_ENABLING:
                        //打开中
                        System.out.println("打开中");
                        break;
                    case WifiManager.WIFI_STATE_DISABLING:
                        //关闭中
                        System.out.println("关闭中");
                        break;

                    case WifiManager.WIFI_STATE_UNKNOWN:
                        //未知
                        System.out.println("未知");
                        onoff.setText("");
                        break;
                }
            }
        }
    }//广播

    private TextView cardModel = null;
    private TextView cardStyle = null;

    public class MyAdapter extends BaseAdapter {
        /**
         * @return 获得数组中的总数
         */
        @Override
        public int getCount() {
            return cardInfos.size();
//            return 10;
        }

        @Override
        public Object getItem(int position) {
            return cardInfos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = null;
            if (convertView == null) {
                //没有旧的View,需创建新的View
                view = View.inflate(MainActivity.this, R.layout.list_item, null);
            } else {
                //可以复用view
                view = convertView;
            }
            //找到需要修改控件对象
            cardModel = (TextView) view.findViewById(R.id.CardModel);
            cardStyle = (TextView) view.findViewById(R.id.CardStyle);
            //获取需要显示的数据
            if (cardInfos.size() > 0) {
                CardInfo cardInfo = cardInfos.get(position);
                cardModel.setText(cardInfo.cardModel);
                cardStyle.setText(cardInfo.cardStyle);
            }
            //测试用的例子
//            cardModel.setText("asdhoaisdkasjd");
//            cardStyle.setText("qweuqwiorqwieu");
            return view;
        }
    }//baseAdapter

}




public class CardInfo {
    public String cardModel;
    public String cardStyle;
    public String toString(){
        return "Card [cardModel="+cardModel+",cardStyle="+cardStyle+"]";
    }
}



//android下的数据库SQLITE
public class MyOpenHelper extends SQLiteOpenHelper {

    /**
     * @param context
     *   数据库文件名字 在内存中创建一个数据库,临时用一下则可以传null
     *    传null
     *  数据库版本号从1开始
     */
    public MyOpenHelper(Context context) {
        super(context, "coalStorage.db", null, 1);
    }

    /**
     * @param db
     * s数据库第一次创建时调用
     * 这里进行表结构创建,数据初始化
     * _id sqlite种的id这一列字段名一般为_id
     * sqlite数据库存的都是字符串
     * 表的修改都在这里操作,
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        //rfidcardstyle 卡的类型
        //rfidcardmodel 卡的型号
        db.execSQL("create table rfidcardinfo(_id integer primary key autoincrement,rfidcardstyle varchar(20),rfidcardmodel varchar(20))");
        Log.d("MyOpenHelper","-----------构建数据库");
    }

    /**
     * @param db
     * @param oldVersion
     * @param newVersion
     * 更新数据库版本,可不做操作
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}



/**
 * Created by zhongtao on 2017/5/19.
 * 接口用于将Socket发送的数据传到Activity
 */
public interface RFIDInfoInterface {
    void getInfo(String info);
}



public class MainServer {
    private RFIDInfoInterface rfidInfoInterface;
    private String cardInfo = null;
    private ServerSocket serverSocket = null;   //socket服务器连接对象
    StringBuffer stringBuffer = new StringBuffer(); //设置缓冲区
    private InputStream inputStream;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 2:
                    cardInfo = msg.obj.toString();
                    Log.d("MainServer","handler  cardInfo--〉"+cardInfo);
                    rfidInfoInterface.getInfo(cardInfo);
                    stringBuffer.setLength(0);
                    break;
            }
        }
    };
    public void setObj(RFIDInfoInterface rfidInfoInterface){
        this.rfidInfoInterface=rfidInfoInterface;
    }

    /*
    服务器端接收数据
    需要注意以下一点:
    服务器端应该是多线程的,因为一个服务器可能会有多个客户端连接在服务器上;
    开启服务器,接收数据
    */
    public void receiveData() {
        Log.d("Mainserver","--receiveData");
        Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                /*指明服务器端的端口号*/
                try {
                    serverSocket = new ServerSocket(8000);
                    Log.d("Mainserver", "serverSocket---->" + serverSocket);

                    GetIpAddress.getLocalIpAddress(serverSocket);
//                    Message message_1 = handler.obtainMessage();
//                    message_1.what = 1;
//                    message_1.obj = "IP:" + GetIpAddress.getIP() + " PORT: " + GetIpAddress.getPort();
                    Log.d("Mainserver", "GetIpAddress.getIP()<<---->" + GetIpAddress.getIP());
                    Log.d("Mainserver", "GetIpAddress.getPort()<<---->" + GetIpAddress.getPort());
//                    handler.sendMessage(message_1);
                    while (true) {
                        Socket socket = null;
                        try {
                            Log.d("Mainserver", "serverSocket<<---->" + serverSocket);
                            socket = serverSocket.accept();
                            Log.d("Mainserver","socket是否连接---->"+socket.isConnected());
                            inputStream = socket.getInputStream();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        new ServerThread(socket, inputStream).start();
                    }//while
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }//run
        };//Thread
        thread.start();
    }

    class ServerThread extends Thread {
        private Socket socket;
        private InputStream inputStream;
        private StringBuffer stringBuffer = MainServer.this.stringBuffer;

        public ServerThread(Socket socket, InputStream inputStream) {
            this.socket = socket;
            this.inputStream = inputStream;
        }

        @Override
        public void run() {
            int len;
            byte[] bytes = new byte[1024];
            boolean isString = false;

            try {
                //在这里需要明白一下什么时候其会等于 -1,其在输入流关闭时才会等于 -1,
                //并不是数据读完了,再去读才会等于-1,数据读完了,最结果也就是读不到数据为0而已;
                while ((len = inputStream.read(bytes)) != -1) {
                    for (int i = 0; i < len; i++) {
                        if (bytes[i] != '\0') {
                            stringBuffer.append((char) bytes[i]);
                        } else {
                            isString = true;
                            break;
                        }
                    }
                    if (isString) {
                        Message message_2 = handler.obtainMessage();
                        message_2.what = 2;
                        message_2.obj = stringBuffer;
                        Log.d("Mainserver","stringBuffer-->"+stringBuffer.toString());
                        handler.sendMessage(message_2); //发送数据
                        isString = false;
                    }
                }
                //当这个异常发生时,说明客户端那边的连接已经断开
            } catch (IOException e) {
                e.printStackTrace();
                try {
                    inputStream.close();
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }


    /*当按返回键时,关闭相应的socket资源*/
    public void closeServer() {
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


public class GetIpAddress {
   
   public static String IP;
   public static int PORT;
   
   public static String getIP(){
      return IP;
   }
   public static int getPort(){
      return PORT;
   }
   public static void getLocalIpAddress(ServerSocket serverSocket){

      try {
         for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();    enumIpAddr.hasMoreElements();){
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    String mIP = inetAddress.getHostAddress().substring(0, 3);
                    if(mIP.equals("192")){
                        IP = inetAddress.getHostAddress();    //获取本地IP
                        PORT = serverSocket.getLocalPort();    //获取本地的PORT
                        Log.e("IP",""+IP);
                        Log.e("PORT",""+PORT);
                    }
                }
            }
      } catch (SocketException e) {
         e.printStackTrace();
      }

   }
}


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.zhongtao.coal_storage_system.MainActivity">

    <TextView
        android:id="@+id/wifistatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="wifi状态:" />
    <TextView
        android:id="@+id/onoff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:background="#ADD8E6"
        android:layout_toRightOf="@id/wifistatus"
         />
    <TextView
        android:id="@+id/wifiname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/wifistatus"
        android:text="wifi名字:" />
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="5dp"
        android:background="#ADD8E6"
        android:layout_below="@+id/wifistatus"
        android:layout_toRightOf="@id/wifiname"
        />
<LinearLayout
    android:id="@+id/ButtonLine"
    android:gravity="center"
    android:layout_marginTop="10dp"
    android:layout_below="@id/wifiname"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/Warehousing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="wareHousing"
        android:text="入库确认"
        />
    <Button
        android:id="@+id/Outhousing"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="出库确认"
        />
    <Button
        android:id="@+id/ShowInventory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="showInventory"
        android:text="显示库存"
        />
</LinearLayout>

    <LinearLayout
        android:id="@+id/listLine"
        android:layout_below="@id/ButtonLine"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:orientation="vertical"
        android:weightSum="2"
        android:layout_width="match_parent"
        android:layout_height="300dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="数据库显示:"
            />

        <ListView
            android:id="@+id/listView"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></ListView>
    </LinearLayout>
<TextView
    android:id="@+id/item"
    android:layout_below="@id/listLine"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="入库条目:"
    />

    <TextView
        android:id="@+id/itemcontent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="sadasd"
        android:layout_below="@+id/item"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/RfidCardModel"
            android:textSize="16sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RFID卡型号:"
            />
        <TextView
            android:id="@+id/CardModel"
            android:textSize="16sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/RfidCardStyle"
            android:textSize="16sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RFID卡类型:"
            />
        <TextView
            android:id="@+id/CardStyle"
            android:textSize="16sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

Socket客户端连接

public class MainActivity extends AppCompatActivity {    private EditText editText_ip,editText_data;    private OutputStream outputStream = null;    private Socket socket = null;    private String ip;    private String data;    private boolean socketStatus = false;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);        setSupportActionBar(toolbar);        editText_ip = (EditText) findViewById(R.id.et_ip);        editText_data = (EditText) findViewById(R.id.et_data);    }    public void connect(View view){        ip = editText_ip.getText().toString();        if(ip == null){            Toast.makeText(MainActivity.this,"please input Server IP",Toast.LENGTH_SHORT).show();        }        Thread thread = new Thread(){            @Override            public void run() {                super.run();                if (!socketStatus) {                    try {                        socket = new Socket(ip,8000);                        if(socket == null){                        }else {                            socketStatus = true;                        }                        outputStream = socket.getOutputStream();                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }        };        thread.start();    }    public void send(View view){        data = editText_data.getText().toString();        if(data == null){            Toast.makeText(MainActivity.this,"please input Sending Data",Toast.LENGTH_SHORT).show();        }else {            //在后面加上 '\0' ,是为了在服务端方便我们去解析;            data = data + '\0';        }        Thread thread = new Thread(){            @Override            public void run() {                super.run();                if(socketStatus){                    try {                        outputStream.write(data.getBytes());                    } catch (IOException e) {                        e.printStackTrace();                    }                }            }        };        thread.start();    }    /*当客户端界面返回时,关闭相应的socket资源*/    @Override    public void onBackPressed() {        super.onBackPressed();        /*关闭相应的资源*/        try {            outputStream.close();            socket.close();        } catch (IOException e) {            e.printStackTrace();        }    }}


原创粉丝点击