MainActivity.java 7.35 KB
package com.xgimi.smartscreen;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.gimi.common.cinema.model.MessageEvent;
import com.gimi.common.cinema.utils.Utils;
import com.xgimi.gimicinema.R;
import com.xgimi.smartscreen.service.ConfigService;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    public static final int UPDATE_CURRENT_CTRL_SCREEN = 0x998;
    private ListView lvDevice;
    private TextView txt_header_current;
    List<String> listData;
    ArrayAdapter<String> adapter;

//    private SwipeRefreshLayout swipeRefreshLayout;

    private boolean isSearching = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        EventBus.getDefault().register(this);
        startService(new Intent(this, ConfigService.class));

        lvDevice = (ListView) findViewById(R.id.lv_device);
        txt_header_current = (TextView) findViewById(R.id.txt_header_current);
        lvDevice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ControlDialog dialog = new ControlDialog(MainActivity.this, listData.get(position));
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);  //去除标题栏
                dialog.show();
            }
        });
        String string = Utils.getString(this, "screen-ip", "");
        int anInt = Utils.getInt(this, "screen-sn", 0);
        if (!TextUtils.isEmpty(string)) {
            txt_header_current.setText("当前控制幕布IP:" + string + ", sn:" + anInt);
        }
        new SearchAsyncTask().execute();

    }

    @Override
    protected void onPause() {
        super.onPause();

        isSearching = false;

//        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void resetCurrent() {
        String string = Utils.getString(this, "screen-ip", "");
        int anInt = Utils.getInt(this, "screen-sn", 0);
        if (!TextUtils.isEmpty(string)) {
            txt_header_current.setText("当前控制幕布IP:" + string + ",sn:" + anInt);
        }
    }

    public void down(View view) {
        MessageEvent msgEvent = new MessageEvent();
        msgEvent.setEventId(SmartScreenBean.DOWNACTION);
        msgEvent.setMessage(Utils.getString(this, "screen-ip", ""));
        EventBus.getDefault().post(msgEvent);
    }

    public void up(View view) {
        MessageEvent msgEvent = new MessageEvent();
        msgEvent.setEventId(SmartScreenBean.UPACTION);
        msgEvent.setMessage(Utils.getString(this, "screen-ip", ""));
        EventBus.getDefault().post(msgEvent);
    }

    private class SearchAsyncTask extends AsyncTask<Void, Integer, String> {

        InetAddress deviceAddress = null;
        DatagramSocket socket = null;

        @Override
        protected String doInBackground(Void... params) {
            isSearching = true;

            try {
                socket = new DatagramSocket();
            } catch (SocketException e) {
                e.printStackTrace();
            }

            //接收
            Thread receiveThread = new Thread(new Runnable() {
                @Override
                public void run() {

                    byte[] dataReceive = new byte[1024];
                    DatagramPacket packetReceive = new DatagramPacket(dataReceive, dataReceive.length);

                    try {
                        socket.receive(packetReceive);

                        String reply = new String(dataReceive, 0, packetReceive.getLength());
                        if (reply.contains("I'm a screen Controller")) {
                            isSearching = false;

                            deviceAddress = packetReceive.getAddress();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            });

            receiveThread.start();

            int cnt = 3; //搜索次数

            while (isSearching) {
                Log.i(TAG, "开始搜索...");

                if (--cnt == 0) {
                    break;
                }

                //发送
                String data = "Are You Screen Controller?";

                DatagramPacket packetSend = null;
                try {
                    packetSend = new DatagramPacket(data.getBytes(), data.getBytes().length,
                            InetAddress.getByName("255.255.255.255"), 12419);
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }

                try {
                    socket.send(packetSend);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            receiveThread.interrupt();

            if (deviceAddress != null) {
                return deviceAddress.toString().substring(1);  //去除ip地址前的斜杠
            } else {
                return null;
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

//            swipeRefreshLayout.setRefreshing(true);

            if (lvDevice.getCount() != 0) {
                adapter.clear();
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

//            swipeRefreshLayout.setRefreshing(false);

            if (s != null) {
                listData = new ArrayList<String>();
                listData.add(s);

                adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, listData);
                lvDevice.setAdapter(adapter);
            } else {
                Toast.makeText(MainActivity.this, "没有搜索到设备,再次下拉搜索", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        switch (messageEvent.getEventId()) {
            case UPDATE_CURRENT_CTRL_SCREEN:
                resetCurrent();
                Log.d(TAG, messageEvent.getMessage());
                break;
        }
    }
}