AskService.java 24.6 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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
package com.xgimi.gimicinema.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.gimi.common.cinema.db.NewDBManager;
import com.gimi.common.cinema.model.BaseData;
import com.gimi.common.cinema.model.Constant;
import com.gimi.common.cinema.model.ControlMessage;
import com.gimi.common.cinema.model.GimiMessage;
import com.gimi.common.cinema.model.GimiSysData;
import com.gimi.common.cinema.model.GimiSysMsg;
import com.gimi.common.cinema.model.MessageEvent;
import com.gimi.common.cinema.model.PlayStatus;
import com.gimi.common.cinema.model.PlayStatusMessage;
import com.gimi.common.cinema.model.SambaMsg;
import com.gimi.common.cinema.model.UdpModel;
import com.gimi.common.cinema.utils.AuthUtils;
import com.gimi.common.cinema.utils.CToast;
import com.gimi.common.cinema.utils.FolderUtils;
import com.gimi.common.cinema.utils.LocalDataUtils;
import com.gimi.common.cinema.utils.MovieMessageUtils;
import com.gimi.common.cinema.utils.NetStatusUtils;
import com.gimi.common.cinema.utils.OpenMMUtils;
import com.gimi.common.cinema.utils.SambaFileCharge;
import com.gimi.common.cinema.utils.SystemUtils;
import com.gimi.common.cinema.utils.T;
import com.gimi.common.cinema.utils.TimeoutCharge;
import com.gimi.common.cinema.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.umeng.analytics.MobclickAgent;
import com.xgimi.gimicinema.BuildConfig;
import com.xgimi.gimicinema.ICinemaControl;
import com.xgimi.gimicinema.R;
import com.xgimi.gimicinema.activity.CinemaConfig;
import com.xgimi.gimicinema.deserializer.GimiMessageDeserializer;
import com.xgimi.gimicinema.deserializer.GimiSysMsgDeserializer;
import com.xgimi.gimicinema.mview.IAskView;
import com.xgimi.gimicinema.presenter.AskPresenter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


/**
 * Created by pc on 2015/1/6
 */
public class AskService extends Service implements IAskView {
    public static final String TAG = "AskService";

    public static final String ASK_SERVICE_ACTION = "com.qnbar.ask.service";
    private static String ROOT_URL = "http://fbs.qnbar.com/";
    private static String ROOT_URL_FOR_TEST = "http://fbs.t.qnbar.com/";
    private static final String STATUS_URL = "apis/rest/Server/getStatus?imei=";
    private static final String MESSAGE_URL = "apis/rest/Server/getMessage?imei=";

    private static final int CUR_PERIOD = 15;

    private Handler handler = new Handler();

    private int unSupport = 0;

    private int statusCount = 0;
    private int messageCount = 0;
    private Context context;
    private SystemUtils systemUtils;
    private StringRequest reqGetStatus;
    private StringRequest reqGetMessage;
    private RequestQueue mQueueSts;
    private RequestQueue mQueueMsg;
    private SharedPreferences sharedPreferences;
    private NewDBManager dbManager;
    private LocalDataUtils localDataUtils;
    private AskPresenter askPresenter;
    private String ip = "";
    private String folder = "";

    private int offlinePromoteCount = 0;

    private int delay = 15;
    private SambaMsg sambaMsg;
    private Gson gson;
    private UdpPostSender sender;
    //    private Type typeStatus;
//    private Type typeMessage;

    // 是否需要完善UDP通信机制,提高通信稳定性
    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        if (!mBound) {
            attemptToBindService();
        }
        initBroadcast();
//        typeStatus = new TypeToken<QnResult<StatusData>>() {
//        }.getType();
//        typeMessage = new TypeToken<QnResult<List<MessageData>>>() {
//        }.getType();
        gson = new GsonBuilder()
                .registerTypeAdapter(GimiSysMsg.class, new GimiSysMsgDeserializer())
                .registerTypeAdapter(GimiMessage.class, new GimiMessageDeserializer())
//                .registerTypeAdapter(typeStatus, new QnMsgDeserializer<StatusData>())
//                .registerTypeAdapter(typeMessage, new QnMsgDeserializer<List<MessageData>>())
                .create();

        askPresenter = new AskPresenter(this);
        localDataUtils = new LocalDataUtils(context);
        dbManager = new NewDBManager(this);
        systemUtils = new SystemUtils();
        mQueueSts = Volley.newRequestQueue(context);
        mQueueMsg = Volley.newRequestQueue(context);
        sharedPreferences = Utils.getSp(context);

        boolean test = sharedPreferences.getBoolean("test", false);
        agentType = Utils.getInt(sharedPreferences, "agent-type", 0);
        if (test) {
            ROOT_URL = ROOT_URL_FOR_TEST;
        }
        Log.d(TAG, "onCreate: " + BuildConfig.MACHINE_TYPE);
        String pid = SystemUtils.getPid(context, BuildConfig.MACHINE_TYPE);
        updateMsg();

        reqGetMessage = new StringRequest(ROOT_URL + MESSAGE_URL + pid,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        AskService.this.handlerMessage(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, " msg error" + error.toString());
            }
        });

        reqGetStatus = new StringRequest(ROOT_URL + STATUS_URL + pid,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        offlinePromoteCount = 0;
                        promoteCount = 0;
                        if (!AuthUtils.checkOfflineAuthTime(context)) {
                            if (!AuthUtils.isFinish(context)) {
                                CToast.makeText(context, "店铺服务已到期,请联系相关工作人员为您续费,否则可能影响后续使用及营业", 8 * 1000).show();
                            } else {
                                showMsg("由于你长期没有续费,系统已暂停你的相关功能使用");
                            }
                        }
                        AskService.this.handleStatus(response);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "status error:" + error.toString());
                boolean pingIp = NetStatusUtils.isAvailableByPing("114.55.207.168");//qnbar ip 通
                boolean pingUrl = TimeoutCharge.ping("fbs.qnbar.com");//qnbar addr 通
                boolean pingLocal = NetStatusUtils.isAvailableByPing(sambaMsg.getIp());//qnbar addr 通

                if (AuthUtils.checkOfflineAuthTime(context)) {
                    if (!pingIp || !pingUrl) {
                        openLed();
                    }
                }

                if (offlinePromoteCount++ >= 3) {
                    return;
                }
                String append = pingLocal ? "电影服务器正常,不影响正常观影" : "电影服务器异常请检查相应配置,否则不能正常观影";
                if ((!pingIp || !pingUrl)) {
                    if (promoteCount++ < 3) {
                        showMsg("机器不能访问远程控制数据,为不影响正常营业,已为您开机," + append);
                    } else {
                        Log.d(TAG, "onErrorResponse: already promote 3 times do nothing " + promoteCount);
                    }
                } else {
                    if (!pingLocal) {
                        showMsg(append);
                    }
                }
            }
        }

        );
        DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(50 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);

        reqGetMessage.setRetryPolicy(retryPolicy);
        reqGetStatus.setRetryPolicy(retryPolicy);

        sender = new UdpPostSender("", 53301, 53301, _handler);

        askPresenter.load(context);
        handler.postDelayed(updateRunnable, 5 * 1000);
//        PollingUtils.startPollingService(context, 60, ProguardService.class, ProguardService.STATUS_ACTION);
    }

    int promoteCount = 0;

    private void handlerMessage(String response) {
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setEventId(1);
        messageEvent.setMessage("handle message");
        EventBus.getDefault().post(messageEvent);
        GimiSysMsg msg = null;
        ProguardService.lastHandlerServerMsg = System.currentTimeMillis();
        try {
            msg = gson.fromJson(response, GimiSysMsg.class);
        } catch (JsonSyntaxException e) {
            uploadCrashMsg("getMessage", response, e.getMessage());
            e.printStackTrace();
        }
        if (msg == null) {
            return;
        }
        StringBuilder buffer = new StringBuilder();
        if (msg.getCode() == 200) {
            for (GimiSysData gimiSysData : msg.getData()) {
                buffer.append(gimiSysData.getMessages().getMsg_content().trim()).append("\n");
            }
            if (!TextUtils.isEmpty(buffer.toString())) {
                if (systemUtils.getYbProp() != 3) {
                    CToast.makeText(context, buffer.toString().trim(), 45 * 1000).show();
                }
            }
            saveGimiAuth(true);
            System.out.println(msg.toString());
            System.out.println(buffer.toString());
        } else if (msg.getCode() == 602) {
            setUnAuthAndToast(msg.getMessage());
            unSupport++;
        }
    }

    private void handleStatus(String response) {
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setEventId(0);
        messageEvent.setMessage("handle status");
        EventBus.getDefault().post(messageEvent);

        GimiMessage gimiMessage = null;
        ProguardService.lastHandlerServerMsg = System.currentTimeMillis();
        try {
            gimiMessage = gson.fromJson(response, GimiMessage.class);
        } catch (JsonSyntaxException e) {
            uploadCrashMsg("getStatus", response, e.getMessage());
            e.printStackTrace();
        }
        if (gimiMessage == null) {
            return;
        }
        System.out.println(gimiMessage.toString());
        if (gimiMessage.getCode() == 200) {
            saveGimiAuth(true);
            if (gimiMessage.getData().getStatus().equals("on")) {
                openLed();
                Constant.messageRun = true;
            } else {
                CToast.makeText(context, "您的观影时间已到,如有需要请到前台续费", 10 * 1000).show();
                new Handler().postDelayed(serviceRunnable, 10 * 1000);
            }
            int delayA = gimiMessage.getData().getDelay();
            Log.d(TAG, "delay time is :" + delayA);
            if (delayA != delay) {
                delay = delayA;
                Log.d(TAG, "delay time change reset");
                statusPool.shutdown();
                statusPool = null;
                startStatusLoop();
            }
        } else if (gimiMessage.getCode() == 602) {
            setUnAuthAndToast(gimiMessage.getMessage());
            unSupport++;
        }
    }

    private void uploadCrashMsg(String type, String msg, String error) {
        HashMap<String, String> map = new HashMap<>();
        map.put("imei", SystemUtils.getPid(context, BuildConfig.MACHINE_TYPE));
        map.put("type", type);
        map.put("msg", msg);
        map.put("error", error);
        MobclickAgent.onEvent(this, "handler_msg_crash", map);
    }

    private void openLed() {
        if (!BuildConfig.MACHINE_TYPE.equals("himedia")) {
            systemUtils.openLed(context);
        }
    }

    private void updateMsg() {
        sambaMsg = Utils.getSambaMsg(sharedPreferences);
        ip = sambaMsg.getIp();
        folder = sambaMsg.getFolder();
    }

    int agentType;

    private void setUnAuthAndToast(String msg) {
        saveGimiAuth(false);
        if (agentType == 5 && AuthUtils.checkOfflineAuthTime(this)) {
            return;
        }
        if (unSupport < 3) {
            if (systemUtils.getYbProp() != 3)
                CToast.makeText(context.getApplicationContext(),
                        TextUtils.isEmpty(msg) ? getString(R.string.no_auth) : msg,
                        10 * 1000).show();
        }
    }

    private Handler _handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            if (msg.what == UdpPostSender.MSG_PARSE_DATA) {
                //maybe need delay
                if (AuthUtils.isFinish(context)) {
                    return;
                }
                String obj = (String) msg.obj;
//                UdpModel udpModel = new Gson().fromJson(obj, UdpModel.class);
//                if (!udpModel.isMulti()) {
//                    playPath(getPlayUrl(udpModel.getMovie_url()));
//                } else {
                //get All list

                ControlMessage controlMessage = gson.fromJson(obj, ControlMessage.class);
                UdpModel udpModel1 = controlMessage.getUdpModel();
                switch (controlMessage.getAction()) {
                    case 0://播放点播电影
                        playPath(getPlayUrl(udpModel1.getMovie_url()));
                        break;
                    case 1://播放点播电影列表
//                        int length = udpModel1.getMovie_urls().length;
//                        String[] trans = new String[length];
//                        for (int i = 0; i < length; i++) {
//                            trans[i] = getPlayUrl(udpModel1.getMovie_urls()[i]);
//                        }
                        playMultiPath(udpModel1.getMovie_urls(), udpModel1.getPosition());
                        break;
                    case 2://返回当前播放状态
                        try {
                            returnCurrentStatus();
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }
            super.dispatchMessage(msg);
        }
//        }
    };

    private void returnCurrentStatus() throws RemoteException {
        PlayStatusMessage statusMessage = new PlayStatusMessage();
        statusMessage.setAction(2);
        PlayStatus status = new PlayStatus();
        status.setCurrentPosition(cinemaControl.getCurrentMoviePosition());
        status.setMovieLength(cinemaControl.getMovieDuration());
        status.setMovieUrls(cinemaControl.getPlayList());
        status.setPath(cinemaControl.getCurrentPath());
        status.setState(cinemaControl.getCurrentStatus());
        statusMessage.setStatus(status);
        String s = gson.toJson(statusMessage);
        sender.sendUDPmsg(s);
    }

    private void playMultiPath(String[] movie_urls, int position) {
        stopMediaPlayer();
        Toast.makeText(context.getApplicationContext(),
                "即将播放新的列表电影", Toast.LENGTH_SHORT).show();
        List<String> result = new ArrayList<>();
        for (String movie_url : movie_urls) {
            result.add("/mnt/samba/" + movie_url);
        }
        try {
            cinemaControl.setPlayList(null);
            cinemaControl.setPlayList(result);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        playPath(result, position);
    }


    private String getPlayUrl(String url) {
        String result;
        if (BuildConfig.MACHINE_TYPE.equals("himedia")) {
            String replace = url.replace(ip, "");
            if (!TextUtils.isEmpty(folder) && (replace.startsWith(folder)
                    || replace.startsWith("//" + folder)
                    || replace.startsWith("/" + folder))) {
                replace = replace.replace(folder, "");
            }
            result = (CinemaConfig.BASIC_ROOT + replace);
        } else {
            result = ("/mnt/samba/" + url);
        }
        return result;
    }

    private String currentPath = "";

    private void playPath(String videoPath) {
        try {
            cinemaControl.setPlayList(null);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(videoPath)) {
            if (SambaFileCharge.fileExist(videoPath)) {
                currentPath = videoPath;
                BaseData bd = new BaseData();
                bd.setPath(videoPath);
                stopMediaPlayer();
                Toast.makeText(context.getApplicationContext(),
                        "即将播放新的电影", Toast.LENGTH_SHORT).show();

                final String path = bd.getPath();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        askPresenter.playMovie(context, path);
                    }
                }, 5000);
                String movieFolderPath = FolderUtils.getMovieFolderPath(videoPath, sambaMsg.getIp(), null);
                int playCount = MovieMessageUtils.getPlayCount(movieFolderPath);
                playCount = playCount + 1;
                MovieMessageUtils.writePlayCount(movieFolderPath, playCount);//update files
                dbManager.updateMovieCount(videoPath, playCount);
            } else {
                T.show(context, "没有电影可以播放,请检查网络或者服务器情况");
                askPresenter.load(context);
                updateMsg();
            }
        } else {
            T.show(context, "没有电影可以播放");
        }
    }

    private void stopMediaPlayer() {
        systemUtils.stopMediaPlayer(context.getApplicationContext());
    }

    private void saveGimiAuth(boolean b) {
        Constant.gimiAuth = b;
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean(Constant.GIMI_AUTHENTICATION, b);
        edit.apply();
    }

    private Runnable updateRunnable = new Runnable() {
        @Override
        public void run() {
            Constant.gimiAuth = sharedPreferences.getBoolean(Constant.GIMI_AUTHENTICATION, true);
            if (Constant.gimiAuth) {
                localDataUtils.updateDb();
            }
        }
    };

    private Runnable serviceRunnable = new Runnable() {
        @Override
        public void run() {
            //停止播放视频 纯后台时不走onResume,还需要启动广告视频
            Intent intent = new Intent(Constant.ACTION_GET_MESSAGE_CLOSE_LED);
            sendBroadcast(intent);
            Constant.messageRun = false;
            if (!BuildConfig.MACHINE_TYPE.equals("himedia")) {
                systemUtils.setLedStatus(false);
            }
            stopMediaPlayer();
            Intent intentHome = new Intent(Intent.ACTION_MAIN);
            intentHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //如果是服务里调用,必须加入new task标识
            intentHome.addCategory(Intent.CATEGORY_HOME);
            startActivity(intentHome);
        }
    };

    private Runnable closeSystem = new Runnable() {
        @Override
        public void run() {
            systemUtils.shutdown(context);
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
//        if (systemUtils.getYbProp() != 3) {
//            if (agentType != 5) {
//                startMessageLoop();
//                startStatusLoop();
//            }
//        }
        return START_STICKY;
    }

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

    @Override
    public void onDestroy() {
        askPresenter.umountSamba();
        if (mBound) {
            unbindService(mServiceConnection);
            mBound = false;
        }
//        unregisterReceiver(myReceiver);
        super.onDestroy();
    }

    @Override
    public void playPath() {
        OpenMMUtils.openMM(context, currentPath, null);
    }

    @Override
    public void playPath(List<String> result, int position) {
        OpenMMUtils.openMM(context, null, result, null, position);
    }

    @Override
    public void showMsg(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    ScheduledExecutorService pool = Executors.newScheduledThreadPool(4);
    ScheduledExecutorService statusPool = Executors.newScheduledThreadPool(4);

    void startStatusLoop() {
        if (statusPool == null) {
            statusPool = Executors.newScheduledThreadPool(4);
        }
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                mQueueSts.add(reqGetStatus);
                statusCount++;
                Log.d(TAG, "run: " + "statusCount = " + statusCount + ",delay = " + delay);
            }
        };
//        statusTimer.schedule(task, 0, delay * 1000);
        statusPool.scheduleAtFixedRate(task, 0, delay * 1000, TimeUnit.MILLISECONDS);
//        pool.
    }

    void startMessageLoop() {
        if (pool == null) {
            pool = Executors.newScheduledThreadPool(4);
        }
        TimerTask himedia = new TimerTask() {
            @Override
            public void run() {
                double v = ((double) (System.currentTimeMillis() / 1000 % 86400)) / 3600;
                if ((v > 18 && v < 24) && !Constant.messageRun && !BuildConfig.MACHINE_TYPE.equals("himedia")) {
                    handler.postDelayed(closeSystem, 5 * 1000);
                }
                if (Constant.messageRun) {
                    // getMessage from server
                    mQueueMsg.add(reqGetMessage);
                    messageCount++;
                }

                Log.d(TAG, "run: " + "messageCount = " + messageCount + ",delay = " + delay);
            }
        };
        pool.scheduleAtFixedRate(himedia, 0, CUR_PERIOD * 1000, TimeUnit.MILLISECONDS);
    }

    //由AIDL文件生成的Java类
    private ICinemaControl cinemaControl = null;

    //标志当前与服务端连接状况的布尔值,false为未连接,true为连接中
    private boolean mBound = false;


    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            cinemaControl = ICinemaControl.Stub.asInterface(service);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
        }
    };

    /**
     * 尝试与服务端建立连接
     */
    private void attemptToBindService() {
        Intent intent = new Intent();
        intent.setAction("com.gimicinema.cinemacontrol");
        intent.setPackage("com.xgimi.gimicinema");
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    public static final String ACTION = "cn.etzmico.broadcastreceiverregister.SENDBROADCAST";
    private BroadcastReceiver myReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
//            Toast.makeText(context, "myReceiver receive", Toast.LENGTH_SHORT)
//                    .show();
            Log.d(TAG, "delay time change reset");
            boolean reset = intent.getBooleanExtra("reset", false);
            if (statusPool != null) {
                statusPool.shutdown();
                statusPool = null;
            }
            if (pool != null) {
                pool.shutdown();
                pool = null;
            }
            if (reset) {
                statusCount = 0;
                messageCount = 0;
                startStatusLoop();
                startMessageLoop();
            }
        }
    };

    private void initBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION);
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(myReceiver, filter);
    }
}