ConfigService.java 19.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
package com.xgimi.smartscreen.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.gimi.common.cinema.model.MessageEvent;
import com.xgimi.smartscreen.SmartScreenBean;
import com.xgimi.smartscreen.confignetwork.ChTask;
import com.xgimi.smartscreen.confignetwork.IChListener;
import com.xgimi.smartscreen.confignetwork.IChResult;
import com.xgimi.smartscreen.confignetwork.IChTask;
import com.xgimi.smartscreen.confignetwork.task.__IChTask;
import com.xgimi.smartscreen.confignetwork.util.NetUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2016/7/26.
 */
public class ConfigService extends Service {

    private String TAG = "ConfigService";
    private WifiAdminSimple mWifiAdmin;
    private String mDeviceIp;
    private int configStat = 0;
    private Timer firstTimer;
    private long waitTime;
    private int findWifiInfoCount = 0;
    private boolean hasTask = false;
    SmartScreenBean smartScreen;

    private int state;
    MessageThread messageThread;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        Log.d("ConfigService", "onStartCommand register event bus");
        EventBus.getDefault().register(this);
        configStat = 0;
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netStateChange, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        if (intent == null)
            return super.onStartCommand(intent, flags, startId);
        if (intent.getIntExtra("boot", 0) == 1) {
            waitTime = System.currentTimeMillis();
            firstTimer = new Timer();
            firstTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    Log.e(TAG, "count time....");
                    if (System.currentTimeMillis() - waitTime > 2 * 60 * 1000) {
                        hasTask = false;
                        firstTimer.cancel();
                        firstTimer = null;
                    }
                }
            }, 0, 1000);
            state = SmartScreenBean.DOWNACTION;
            hasTask = true;
            getNetStat();
        }

      /*  String action = intent.getAction();
        if ("com.xgimi.smartscreen.ACTION.CONTROL".equals(action)) {
            state = intent.getIntExtra("CONTROL", -1);
            String ip = intent.getStringExtra("CONTROLIP");
            if (state >= 0) {
                Control(ip, state);
            }
        } else if ("com.xgimi.smartscreen.ACTION.SEARCH".equals(action)) {
            new SearchAsyncTask().execute();
        } else if ("com.xgimi.smartscreen.ACTION.BIND".equals(action)) {
            String bindInfo = intent.getStringExtra("BINDINFO");
            XgimiSettingsSP.putString(ConfigService.this, "BINDINFO", bindInfo);
            Intent notifyIntent = new Intent("com.xgimi.smartscreen.ACTION.DEVICEBIND");
            sendBroadcast(notifyIntent);
        }*//*else if("com.xgimi.smartscreen.ACTION.POWEROFF".equals(action)){
            state = SmartScreenBean.UPACTION;
            hasTask = true;
            String bindInfo = XgimiSettingsSP.getString(ConfigService.this,"BINDINFO");
            if(!StringUtils.isEmpty(bindInfo)){
                Gson gson = new Gson();
                try {
                    smartScreen = gson.fromJson(bindInfo,SmartScreenBean.class);
                    if(smartScreen!=null&&!StringUtils.isEmpty(smartScreen.ip)){
                        handler.sendEmptyMessage(999);
                        handler.sendEmptyMessageDelayed(999,300);
                        handler.sendEmptyMessageDelayed(999,600);
                        handler.sendEmptyMessageDelayed(999,900);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }*/
        return super.onStartCommand(intent, flags, startId);
    }

    private void Control(String ip, int stat) {
        if (messageThread == null)
            messageThread = new MessageThread();
        messageThread.setIp(ip);
        messageThread.setMode(stat);
        new Thread(messageThread).start();
    }

    public class MessageThread implements Runnable {
        final int PORT = 8009;
        String cmd, ip;

        public void setIp(String ip) {
            this.ip = ip;
        }

        public void setMode(int mode) {
            JSONObject dataUp = new JSONObject();
            try {
                dataUp.put("cmd", 2);
                dataUp.put("action", mode);
                cmd = dataUp.toString();
            } catch (JSONException e) {
                e.printStackTrace();
                cmd = null;
            }
        }

        @Override
        public void run() {
            if (TextUtils.isEmpty(cmd)) {
                return;
            }
            BufferedReader br = null;
            PrintWriter pw = null;
            Socket socket = null;
            try {
                socket = new Socket(ip, PORT);
                socket.setSoTimeout(1000);
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                pw = new PrintWriter(socket.getOutputStream());
                pw.write(cmd);
                pw.flush();
                String data = null;
                while ((data = br.readLine()) != null) {
                    Log.i(TAG, "接收到的数据:" + data);
                    Message msg = new Message();
                    msg.what = 0x123;
                    msg.obj = data;
                    handler.sendMessage(msg);
                }
            } catch (SocketTimeoutException e) {
                Log.i(TAG, "网络连接超时!");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (pw != null) {
                        pw.close();
                    }
                    if (br != null) {
                        br.close();
                    }
                    if (socket != null) {
                        socket.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 998) {
                Toast.makeText(ConfigService.this, "recv ", Toast.LENGTH_SHORT).show();
            } else if (msg.what == 999) {
                Log.e(TAG, "shut down !!!");
                Control(smartScreen.ip, state);
            } else if (msg.what == 1000) {
                WifiInfo wifiInfo = (WifiInfo) msg.obj;
                startConfig(wifiInfo.Ssid, wifiInfo.Password);
            } else if (msg.what == 0x123) {
                String data = (msg.obj).toString();
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    int cmd = jsonObject.getInt("cmd");
                    if (cmd == 2) {
                        int result = jsonObject.getInt("result");
                        if (result == 1) { //成功
                            Toast.makeText(ConfigService.this, "操作成功", Toast.LENGTH_SHORT).show();
                            Log.e(TAG, "操作成功");
                        } else {
                            if (result == 0) {  //失败
                                Toast.makeText(ConfigService.this, "操作失败", Toast.LENGTH_SHORT).show();
                                Log.e(TAG, "操作失败");
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private void getNetStat() {
        Log.d(TAG, "getNetStat");
        int stat = XgimiSettingsSP.getInt(ConfigService.this, "AUTOSCREEN");
        if (stat == 0) {
            return;
        }
        if (NetUtil.isConnected(ConfigService.this)) {
            Log.e(TAG, "SearchAsyncTask");
            new SearchAsyncTask().execute();
        }
    }

    private BroadcastReceiver netStateChange = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            String action = intent.getAction();
            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
                Log.d(TAG, "网络状态已经改变");
                if (NetUtil.isConnected(ConfigService.this)) {
                    new SearchAsyncTask().execute();
                }
            }
        }
    };

    private void findWifiInfo() {
        findWifiInfoCount++;
        Log.d(TAG, "findWifiInfo" + findWifiInfoCount);
        if (mWifiAdmin == null) {
            mWifiAdmin = new WifiAdminSimple(this);
        }
        String apSsid = mWifiAdmin.getWifiConnectedSsid();
        if (TextUtils.isEmpty(apSsid)) {
            return;
        }
    }

    private void startConfig(String apSsid, String apPassword) {
        Log.d(TAG, "startConfig");
        String apBssid = mWifiAdmin.getWifiConnectedBssid();
        String isSsidHiddenStr = "YES";
        int[] tastResultCount = {0, 1, 2, 3, 4, 5};
        String taskResultCountStr = Integer.toString(tastResultCount[1]); //设置任务的数量为1个
        if (__IChTask.DEBUG) {
            Log.d(TAG, "mBtnConfig is clicked, mEdtApSsid = " + apSsid + ", " + " mEdtApPassword = " + apPassword);
        }
        new AsyncTask3().execute(apSsid, apBssid, apPassword, isSsidHiddenStr, taskResultCountStr);
    }

    private void onChResultAddedPerform(final IChResult result) {
        String text = result.getBssid() + " 已连接到wifi";
        Log.e(TAG, "onChResultAddedPerform:" + text);
    }

    private IChListener myListener = new IChListener() {

        @Override
        public void onChResultAdded(final IChResult result) {
            onChResultAddedPerform(result);
        }
    };

    private class AsyncTask3 extends AsyncTask<String, Void, List<IChResult>> {

        private IChTask mChTask;
        // without the lock, if the user tap confirm and cancel quickly enough,
        // the bug will arise. the reason is follows:
        // 0. task is starting created, but not finished
        // 1. the task is cancel for the task hasn't been created, it do nothing
        // 2. task is created
        // 3. Oops, the task should be cancelled, but it is running
        private final Object mLock = new Object();

        @Override
        protected List<IChResult> doInBackground(String... params) {
            int taskResultCount = -1;
            synchronized (mLock) {
                String apSsid = params[0];
                String apBssid = params[1];
                String apPassword = params[2];
                String isSsidHiddenStr = params[3];
                String taskResultCountStr = params[4];
                boolean isSsidHidden = false;
                if (isSsidHiddenStr.equals("YES")) {
                    isSsidHidden = true;
                }
                taskResultCount = Integer.parseInt(taskResultCountStr);
                mChTask = new ChTask(apSsid, apBssid, apPassword, isSsidHidden, ConfigService.this);
                mChTask.setChListener(myListener);
            }
            List<IChResult> resultList = mChTask.executeForResults(taskResultCount);
            return resultList;
        }

        @Override
        protected void onPostExecute(List<IChResult> result) {
            IChResult firstResult = result.get(0);
            // check whether the task is cancelled and no results received
            Log.e(TAG, "onPostExecute IChResult");
            if (!firstResult.isCancelled()) {
                int count = 0;
                // max results to be displayed, if it is more than maxDisplayCount,
                // just show the count of redundant ones
                final int maxDisplayCount = 5;
                // the task received some results including cancelled while
                // executing before receiving enough results
                String ip = "";
                if (firstResult.isSuc()) {
                    StringBuilder sb = new StringBuilder();
                    for (IChResult resultInList : result) {
                        sb.append("配置成功" + "\n" + "BSSID = " + resultInList.getBssid() + "\n" + "InetAddress = " + resultInList.getInetAddress().getHostAddress());
                        ip = resultInList.getInetAddress().getHostAddress();
                        count++;
                        if (count >= maxDisplayCount) {
                            break;
                        }
                    }
                    if (count < result.size()) {
                        sb.append("\n有 " + (result.size() - count) + " 个结果未显示\n");
                    }
                    Log.e(TAG, "test:start SearchAsyncTask;" + sb.toString());
                    if (hasTask)
                        Control(ip, state);
                } else {
                    Log.e(TAG, "onPostExecute isSuc = false");
                }
            } else {
                Log.e(TAG, "onPostExecute isCancelled");
            }
        }
    }

    private class SearchAsyncTask extends AsyncTask<Void, Integer, String> {
        InetAddress deviceAddress = null;
        DatagramSocket socket = null;
        boolean isSearching = false;

        @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();
                        Log.i(TAG, "receive...cnt" + e.toString());
                    }
                }

            });
            receiveThread.start();
            int cnt = 3; //搜索次数

            while (isSearching) {
                Log.i(TAG, "开始搜索...cnt" + cnt);
                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();
                    Log.e(TAG, "send IOException" + e.toString());
                }

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Log.e(TAG, "sleep InterruptedException" + e.toString());
                }
            }
            receiveThread.interrupt();
            if (deviceAddress != null) {
                return deviceAddress.toString().substring(1);  //去除ip地址前的斜杠
            } else {
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.e(TAG, "ip:" + s);
            if (!TextUtils.isEmpty(s)) {
                SmartScreenBean smartScreenBean = new SmartScreenBean();
                smartScreenBean.ip = s;
                smartScreenBean.name = "极米智能幕布";
                smartScreenBean.state = 0;
//                String bindInfo = new Gson().toJson(smartScreenBean, SmartScreenBean.class);
//                XgimiSettingsSP.putString(ConfigService.this, "BINDINFO", bindInfo);
//                Intent notifyIntent = new Intent("com.xgimi.smartscreen.ACTION.DEVICEBIND");
//                sendBroadcast(notifyIntent);
                if (hasTask) {
                    Control(s, state);
                    hasTask = false;
                }
            } else {
                Log.e(TAG, "没有发现设备!");
//                XgimiSettingsSP.putString(ConfigService.this, "BINDINFO", "");
//                Intent notifyIntent = new Intent("com.xgimi.smartscreen.ACTION.NODEVICE");
//                sendBroadcast(notifyIntent);
            }
        }
    }


    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        EventBus.getDefault().unregister(this);
        if (firstTimer != null) {
            firstTimer.cancel();
            firstTimer = null;
        }
        unregisterReceiver(netStateChange);
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent) {
        switch (messageEvent.getEventId()) {
            case SmartScreenBean.UPACTION:
                Log.d(TAG, "SmartScreenBean.UPACTION");
                Control(messageEvent.getMessage(), messageEvent.getEventId());
                break;
            case SmartScreenBean.DOWNACTION:
                Log.d(TAG, "SmartScreenBean.DOWNACTION");
                Control(messageEvent.getMessage(), messageEvent.getEventId());
                break;
            case SmartScreenBean.STOPACTION:
                Log.d(TAG, "SmartScreenBean.STOPACTION");
                Control(messageEvent.getMessage(), messageEvent.getEventId());
                break;
        }
    }
}