MainApplication.java 13.6 KB
package com.metroapp;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.webkit.WebView;

import com.BV.LinearGradient.LinearGradientPackage;
import com.alibaba.fastjson.JSON;
import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;
import com.amap.api.fence.GeoFence;
import com.amap.api.fence.GeoFenceClient;
import com.amap.api.fence.GeoFenceListener;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.DPoint;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.beefe.picker.PickerViewPackage;
import com.brentvatne.react.ReactVideoPackage;
import com.elvishew.xlog.LogConfiguration;
import com.elvishew.xlog.XLog;
import com.elvishew.xlog.printer.Printer;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy;
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator;
import com.facebook.react.ReactApplication;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.iou90.autoheightwebview.AutoHeightWebViewPackage;
import com.lwansbrough.RCTCamera.RCTCameraPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.imagepicker.ImagePickerPackage;
import com.mehcode.reactnative.splashscreen.SplashScreenPackage;
import com.metroapp.constant.Constant;
import com.metroapp.nativemodules.BluetoothModule;
import com.metroapp.rnpackage.BluetoothPackage;
import com.metroapp.rnpackage.UpdateVersionPackage;
import com.metroapp.utils.XNVersionService;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import java.util.Arrays;
import java.util.IllegalFormatCodePointException;
import java.util.List;

import static com.amap.api.fence.GeoFenceClient.GEOFENCE_IN;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_OUT;
import static com.amap.api.fence.GeoFenceClient.GEOFENCE_STAYED;
import static com.umeng.commonsdk.stateless.UMSLEnvelopeBuild.mContext;

public class MainApplication extends Application implements ReactApplication {

  //定义接收广播的action字符串
  public static final String GEOFENCE_BROADCAST_ACTION = "com.location.apis.geofencedemo.broadcast";
  //声明AMapLocationClient类对象
  private AMapLocationClient mLocationClient = null;

  private GeoFenceClient mGeoFenceClient = null;

  private LatLng oldLatLng = null;

  public static  MainApplication _this;

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
              new MainReactPackage(),
              new AutoHeightWebViewPackage(),
              new RCTCameraPackage(),
              new ImagePickerPackage(),
              new LinearGradientPackage(),
              new PickerViewPackage(),
              new ReactVideoPackage(),
              new SplashScreenPackage(),
              new BluetoothPackage(),
              new UpdateVersionPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  private Context context;
  @Override
  public void onCreate() {
    super.onCreate();
    _this = this;
    SoLoader.init(this, /* native exopackage */ false);
    context = this;
    //启动保活service
    Intent intent = new Intent(this, GrayService.class);
    startService(intent);

    if(BuildConfig.DEBUG)
    {
      WebView.setWebContentsDebuggingEnabled(true);
    }

    LogConfiguration config = new LogConfiguration.Builder()
            .tag("METRO")                                         // 指定 TAG,默认为 "X-LOG"
            .build();


    Printer filePrinter = new FilePrinter                      // 打印日志到文件的打印器
            .Builder(Environment.getExternalStorageDirectory()+ "/1111MetroLog")                              // 指定保存日志文件的路径
            .fileNameGenerator(new DateFileNameGenerator())        // 指定日志文件名生成器,默认为 ChangelessFileNameGenerator("log")
            .backupStrategy(new NeverBackupStrategy())            // 指定日志文件备份策略,默认为 FileSizeBackupStrategy(1024 * 1024)
            .build();
    XLog.init(config,filePrinter);

    // 高德地图定位
    initMapLocation();
    //友盟
    UMConfigure.init(this,UMConfigure.DEVICE_TYPE_PHONE, null);
    MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
    //管理activity生命周期,用于友盟检测日活
    registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
      @Override
      public void onActivityCreated(Activity activity, Bundle bundle) {

      }

      @Override
      public void onActivityStarted(Activity activity) {

      }

      @Override
      public void onActivityResumed(Activity activity) {
        MobclickAgent.onResume(context);

      }

      @Override
      public void onActivityPaused(Activity activity) {
        MobclickAgent.onPause(context);

      }

      @Override
      public void onActivityStopped(Activity activity) {
      }

      @Override
      public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

      }

      @Override
      public void onActivityDestroyed(Activity activity) {
      }
    });

  }
  static final String LOG_TAG_LOCATION = "locationLog";
  private void initMapLocation(){
    if (null == mLocationClient) {
      //初始化client
      mLocationClient = new AMapLocationClient(getApplicationContext());
      //设置定位参数
      mLocationClient.setLocationOption(getDefaultOption());
      // 设置定位监听
      mLocationClient.setLocationListener(new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation loc) {
          Log.d(LOG_TAG_LOCATION, "onLocationChanged: ");
          try {
            if (null != loc) {
              //可在其中解析amapLocation获取相应内容。
              if (loc.getErrorCode() == 0) {
                LatLng newLatLng = new LatLng(loc.getLatitude(),loc.getLongitude());
                if (null == oldLatLng){
                  Log.d(LOG_TAG_LOCATION,"定位成功-初次定位");
                  oldLatLng = newLatLng;
                  //创建一个中心点坐标
                  DPoint centerPoint = new DPoint();
                  centerPoint.setLatitude(loc.getLatitude());
                  centerPoint.setLongitude(loc.getLongitude());
                  addGeoFence(centerPoint);
                }else{
                  float distance = AMapUtils.calculateLineDistance(newLatLng,oldLatLng);
                  distance = Math.round(distance);// 四舍五入
                  if (distance > 50){
                    Log.d(LOG_TAG_LOCATION,"定位成功-累计位移超过50米,重新取得地理围栏");
                    oldLatLng = newLatLng;
                    //创建一个中心点坐标
                    DPoint centerPoint = new DPoint();
                    centerPoint.setLatitude(loc.getLatitude());
                    centerPoint.setLongitude(loc.getLongitude());
                    addGeoFence(centerPoint);
                  }else{
                    Log.d(LOG_TAG_LOCATION,"定位成功-但位移在50米内,不更新地理围栏");
                  }
                }
                //创建一个中心点坐标
//                DPoint centerPoint = new DPoint();
//                centerPoint.setLatitude(loc.getLatitude());
//                centerPoint.setLongitude(loc.getLongitude());
//                addGeoFence(centerPoint);
              } else {
                // 定位返回的loc包含失败信息
                Log.d(LOG_TAG_LOCATION,"定位返回的loc包含失败信息");
              }
            }else{
              // 定位返回的loc为空
              Log.d(LOG_TAG_LOCATION,"定位返回的loc为空");
            }
          } catch (Exception ex) {
            Log.d(LOG_TAG_LOCATION,"定位捕捉到异常");
            ex.printStackTrace();
          }
        }
      });
    }
  }

  /**
   * 默认的定位参数
   */
  private AMapLocationClientOption getDefaultOption() {
    AMapLocationClientOption mOption = new AMapLocationClientOption();
    mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选,设置定位模式,可选的模式有高精度、仅设备、仅网络。默认为高精度模式
    mOption.setGpsFirst(true);//可选,设置是否gps优先,只在高精度模式下有效。默认关闭
    mOption.setHttpTimeOut(30000);//可选,设置网络请求超时时间。默认为30秒。在仅设备模式下无效
    mOption.setInterval(5000);//可选,设置定位间隔。默认为2秒
    mOption.setNeedAddress(true);//可选,设置是否返回逆地理地址信息。默认是true
    mOption.setOnceLocation(false);//可选,设置是否单次定位。默认是false
    mOption.setOnceLocationLatest(false);//可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用
    AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选, 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
    mOption.setSensorEnable(false);//可选,设置是否使用传感器。默认是false
    mOption.setWifiScan(true); //可选,设置是否开启wifi扫描。默认为true,如果设置为false会同时停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差
    mOption.setMockEnable(true);//如果您希望位置被模拟,请通过setMockEnable(true);方法开启允许位置模拟
    mOption.setLocationCacheEnable(false);//关闭缓存机制
    return mOption;
  }

  private void addGeoFence(DPoint point){
    if(null == mGeoFenceClient){
      mGeoFenceClient = new GeoFenceClient(getApplicationContext());
      //设置希望侦测的围栏触发行为,默认只侦测用户进入围栏的行为
      mGeoFenceClient.setActivateAction(GEOFENCE_IN|GEOFENCE_OUT|GEOFENCE_STAYED);

      mGeoFenceClient.setGeoFenceListener(new GeoFenceListener() {
        @Override
        public void onGeoFenceCreateFinished(List<GeoFence> list, int i, String s) {
          if(i == GeoFence.ADDGEOFENCE_SUCCESS){
            //添加围栏成功!!
            //geoFenceList是已经添加的围栏列表,可据此查看创建的围栏
            Log.d(LOG_TAG_LOCATION,"添加围栏成功!!");
          } else {
            //添加围栏失败!!
            Log.d(LOG_TAG_LOCATION,"添加围栏失败!!");
          }
        }
      });
      // 创建并设置PendingIntent
      mGeoFenceClient.createPendingIntent(GEOFENCE_BROADCAST_ACTION);
      // 注册广播
      registerGeoFenceReceiver();
    }else{
      //清除所有围栏
//      mGeoFenceClient.removeGeoFence();
    }
    mGeoFenceClient.addGeoFence("地铁站","150500",point,150F,1,"poi_1");
  }

  class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      if (intent.getAction().equals(GEOFENCE_BROADCAST_ACTION)) {
        //解析广播内容
        //获取Bundle
        Bundle bundle = intent.getExtras();
        //获取自定义的围栏标识:
        String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
        String poiName = "";
        ////获取自定义的围栏标识:
//        String customId = bundle.getString(GeoFence.BUNDLE_KEY_CUSTOMID);
        ////获取围栏ID:
//        String fenceId = bundle.getString(GeoFence.BUNDLE_KEY_FENCEID);
        ////获取当前有触发的围栏对象:
        GeoFence fence = bundle.getParcelable(GeoFence.BUNDLE_KEY_FENCE);
        if (null != fence && null != fence.getPoiItem()){
          poiName = fence.getPoiItem().getPoiName();
        }
        WritableMap map = new WritableNativeMap();
        map.putString("requestData",poiName);

        BluetoothModule.sendEvent("locationData",map);
        int status = bundle.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS);
        switch (status){
          case GEOFENCE_IN:
            Log.d(LOG_TAG_LOCATION,"进地铁站");
            BluetoothModule.sendEvent("locationData",map);
            break;
          case GEOFENCE_OUT:
            Log.d(LOG_TAG_LOCATION,"出地铁站");
            //BluetoothModule.sendEvent("locationData",map);
            break;
          case GEOFENCE_STAYED:
            Log.d(LOG_TAG_LOCATION,"在地铁站");
            break;
          default:
            break;
        }
      }
    }
  }

  //注册广播接收者
  private void registerGeoFenceReceiver() {
    IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
    filter.addAction(GEOFENCE_BROADCAST_ACTION);
    MyBroadcastReceiver mBReceiver = new MyBroadcastReceiver();
    getApplicationContext().registerReceiver(mBReceiver,filter);
  }

  public void startMapLocation(){
    // 启动定位
    if(mLocationClient.isStarted() == false){
      mLocationClient.startLocation();
    }
  }
}