Ver código fonte

解决冲突

Ray Zhang 7 anos atrás
pai
commit
ea75eaf8ba

+ 2 - 2
ApexDrivers/RAUtilsLibrary/build.gradle

@@ -4,8 +4,8 @@ android {
     compileSdkVersion 27
     defaultConfig {
 //        applicationId "com.usai.redant.rautils"
-        minSdkVersion 23
-        targetSdkVersion 27
+        minSdkVersion 21
+        targetSdkVersion 26
         versionCode 1
         versionName "1.0"
         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

+ 6 - 4
ApexDrivers/RAUtilsLibrary/src/main/AndroidManifest.xml

@@ -37,10 +37,12 @@
         <!-- android:enabled="true" -->
         <!-- android:exported="true" /> -->
 
-        <!--<receiver-->
-            <!--android:name=".Receiver.RABroadcastReceiver"-->
-            <!--android:enabled="true"-->
-            <!--android:exported="false"></receiver>-->
+        <receiver
+            android:name=".Receiver.RABroadcastReceiver"
+            android:enabled="true"
+            android:exported="false">
+
+        </receiver>
     </application>
 
 </manifest>

+ 678 - 0
ApexDrivers/RAUtilsLibrary/src/main/java/com/usai/redant/rautils/AppImpl.java

@@ -0,0 +1,678 @@
+package com.usai.redant.rautils;
+
+import android.Manifest;
+import android.app.AlarmManager;
+import android.app.Application;
+import android.app.Notification;
+import android.app.NotificationManager;
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.content.SharedPreferences;
+import android.content.pm.PackageManager;
+import android.location.Location;
+import android.location.LocationListener;
+import android.location.LocationManager;
+import android.net.ConnectivityManager;
+import android.net.NetworkInfo;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.SystemClock;
+import android.support.v4.app.ActivityCompat;
+import android.text.TextUtils;
+import android.util.Log;
+
+import com.usai.redant.rautils.Receiver.RABroadcast;
+import com.usai.redant.rautils.Upload.RAUploadManager;
+import com.usai.redant.rautils.Utils.Network;
+import com.usai.redant.rautils.Utils.dbgUtil;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.ArrayList;
+
+public abstract class AppImpl extends Application {
+    protected static AppImpl mApp;
+
+    private static final String TAG = "AppImpl";
+
+    public static final int DEFAULT_LOCATION_TIMEINTERVAL = 60 * 1000;
+    public static final int DEFAULT_DISTANCE = 60 * 50;
+    public static final int DEFAULT_PUSHNOTIFICATION_TIMEINTERVAL = 30 * 1000;
+
+    public static final int FLAG_MODULE_NONE = 0;
+    public static final int FLAG_MODULE_LOCATION = 1 << 1;
+    public static final int FLAG_MODULE_NOTIFICATION = 1 << 2;
+    public static final int FLAG_MODULE_UPLOAD = 1 << 3;
+//    public static final int FLAG_LOCATION_SERVICE = 1<<1;
+
+    // service setup
+    protected int service_flag = FLAG_MODULE_NONE;
+    private IntentFilter msgFilter = new IntentFilter();
+
+    protected abstract void Setup();
+
+
+    // sub function upload
+    public interface ModuleUpload {
+
+    }
+    public void initModuleUpload(AppImpl.ModuleUpload uploadCallback) {
+        service_flag = service_flag | FLAG_MODULE_UPLOAD;
+//        this.upload = locationCallback;
+    }
+
+    private RAUploadManager uploadManager = null;
+
+    public RAUploadManager getUploadManager() {
+        return uploadManager;
+    }
+
+    // sub function location
+    LocationListener locationListener = null;
+    LocationManager locationManager = null;
+    int locationTracing_timeInterval = DEFAULT_LOCATION_TIMEINTERVAL;
+    int locationTracing_distance = DEFAULT_DISTANCE;
+    //    protected abstract void onLocationChanged(Location location);
+    private AppImpl.ModuleLocation locationCallback = null;
+
+    public interface ModuleLocation {
+
+
+        public abstract  Location RequestCachedLocation();
+//        public abstract void RequestLocation_ByBroadcast(String receiverID);
+
+        public abstract void onLocationChanged(Location location);
+//        public abstract void onLogin();
+//		public abstract void onLogout();
+    }
+
+    public void initModuleLocation(AppImpl.ModuleLocation locationCallback) {
+        service_flag = service_flag | FLAG_MODULE_LOCATION;
+        this.locationCallback = locationCallback;
+    }
+
+
+    // sub function Notification
+    protected String url_checknotification = null;
+    int pushcheck_timeInterval = DEFAULT_PUSHNOTIFICATION_TIMEINTERVAL;
+    protected static final int NOTIFICATION_TYPE_PUSHNOTIFICATION = 0;
+    protected static final int NOTIFICATION_TYPE_SILENCECOMMAND = 1;
+    protected boolean enable_pushNotification = false;
+
+    //    protected abstract Notification prepareNotification(JSONObject msg);
+//    protected abstract void handleSilenceMessage(JSONObject msg);
+    public interface ModulePushNotification {
+        public abstract Notification prepareNotification(JSONObject msg);
+
+        public abstract void handleSilenceMessage(JSONObject msg);
+    }
+
+    public void initModuleNotification(AppImpl.ModulePushNotification pushNotificationCallback, String url_checknotification) {
+        service_flag = service_flag | FLAG_MODULE_NOTIFICATION;
+        this.url_checknotification = url_checknotification;
+        this.pushNotificationCallback = pushNotificationCallback;
+    }
+
+    private AppImpl.ModulePushNotification pushNotificationCallback = null;
+    private AppImpl.checkPushTask m_task = null;
+
+    class checkPushTask extends AsyncTask<Void, Void, Boolean> {
+        int errorcode;
+        String content = null;
+        Context mcontext;
+
+        public checkPushTask(Context context) {
+            mcontext = context;
+        }
+
+        @Override
+        protected Boolean doInBackground(Void... params) {
+            Log.d("SearchTask", "doInBackground");
+
+            if (!Network.isNetworkAvailable(AppImpl.getInstance()))
+
+            {
+                errorcode = Network.RESULT_NET_NOTAVAILABLE;
+                return false;
+            }
+            String jstr = "";
+            jstr = Network.check_push(mcontext, new Bundle(), url_checknotification);
+            // if (module_name.equals("Announcements"))
+            // jstr = Network.get_announcements(lastid, limit);
+            // else
+            // jstr = Network.get_marketnews(lastid, limit);
+            if (jstr == null || jstr.length() <= 0) {
+                // Log.d(TAG, "json is wrong");
+
+                errorcode = Network.RESULT_NET_ERROR;
+                return false;
+            }
+
+            content = jstr;
+            return true;
+        }
+
+        @Override
+        protected void onPostExecute(Boolean success) {
+            String tag = "onPostExec";
+            Log.i(tag, "entry");
+            m_task = null;
+
+
+            if (success) {
+                JSONObject jsobj;
+                //
+                // array = new JSONArray(json);
+                try {
+                    jsobj = new JSONObject(content);
+
+                    int count = jsobj.getInt("count");
+
+                    for (int i = 0; i < count; i++) {
+                        JSONObject msg = jsobj.getJSONObject("msg_" + i);
+                        int type = msg.getInt("type");
+                        if (type == NOTIFICATION_TYPE_SILENCECOMMAND) {
+
+                            pushNotificationCallback.handleSilenceMessage(msg);
+                            Intent intent = new Intent(RABroadcast.EVENT_SILENCECOMMAND);
+                            intent.putExtra("msg", msg.toString());
+                            sendBroadcast(intent);
+
+                        } else {
+                            pushNotification(msg);
+
+                            Intent intent = new Intent(RABroadcast.EVENT_PUSHNOTIFICATION);
+                            intent.putExtra("msg", msg.toString());
+                            sendBroadcast(intent);
+
+
+                        }
+                    }
+
+
+                } catch (JSONException e) {
+                    // TODO Auto-generated catch block
+                    e.printStackTrace();
+                }
+
+            }
+
+            super.onPostExecute(success);
+        }
+
+        @Override
+        protected void onCancelled() {
+            m_task = null;
+            // showProgress(false);
+        }
+    }
+
+
+    public void pushNotification(JSONObject msg) {
+
+        if (enable_pushNotification) {
+
+            boolean bsound = true;
+//                    mcontext.getSharedPreferences(
+//                    "setting", 0).getBoolean(
+//                    "notifications_new_message_sound", true);
+            boolean bvibrate = true;
+//            mcontext.getSharedPreferences(
+//                    "setting", 0).getBoolean(
+//                    "notifications_new_message_vibrate", true);
+            NotificationManager nManager = (NotificationManager)
+                    getSystemService(Context.NOTIFICATION_SERVICE);
+
+/*
+       此部分在虚函数 prepareNotificaiton 中实现
+            Intent intent = new Intent(mcontext,
+                    FunctionSelectActivity.class);
+            intent.putExtra("launcher", "notification");
+
+            PendingIntent pintent = PendingIntent.getActivity(
+                    this, 0, intent,
+                    PendingIntent.FLAG_UPDATE_CURRENT);
+
+
+            Notification.Builder builder = new Notification.Builder(mcontext);//新建Notification.Builder对象
+            String ntitle = "";
+            int number = ApexTrackingApplication.ncount++;
+            if (number > 1)
+                ntitle=number
+                        + " "
+                        + ApexTrackingApplication
+                        .get_instance()
+                        .getString(
+                                R.string.str_mnotification_title);
+            else
+                ntitle = ApexTrackingApplication
+                        .get_instance()
+                        .getString(
+                                R.string.str_notification_title);
+
+            builder.setContentTitle(ntitle);//设置标题
+            builder.setContentText(ApexTrackingApplication
+                    .get_instance()
+                    .getString(
+                            R.string.str_notification_text)
+                    + date);//设置内容
+            builder.setSmallIcon(R.drawable.ic_launcher);//设置图片
+            builder.setContentIntent(pintent);//执行intent
+
+
+            */
+            Notification notification = pushNotificationCallback.prepareNotification(msg);//builder.getNotification();//将builder对象转换为普通的notifications
+            notification.defaults = Notification.DEFAULT_ALL;
+
+//            if (bsound && bvibrate)
+//                notification.defaults = Notification.DEFAULT_ALL;
+//            else if (bsound)
+//                notification.defaults = Notification.DEFAULT_SOUND
+//                        | Notification.DEFAULT_LIGHTS;
+//            else if (bvibrate)
+//                notification.defaults = Notification.DEFAULT_VIBRATE
+//                        | Notification.DEFAULT_LIGHTS;
+            notification.flags = Notification.FLAG_AUTO_CANCEL;
+//            notification.number = number; //number 是不是不需要了?
+
+            nManager.notify(R.layout.support_simple_spinner_dropdown_item, notification);
+        }
+    }
+
+    public void checkpush(Context context) {
+
+        if (m_task != null) {
+            return;
+        }
+        // mStatusMessageView.setText(R.string.str_Loading);
+        // showProgress(true);
+        m_task = new AppImpl.checkPushTask(context);
+
+        // TextView text_page = (TextView) view_page_footer
+        // .findViewById(R.id.text_page);
+        // text_page.setText("Loading...");
+        // text_page.setEnabled(false);
+        m_task.execute();
+
+    }
+
+
+
+    private BroadcastReceiver receiver = new BroadcastReceiver() {
+
+        public void onReceive(Context context, Intent intent) {
+            String action = intent
+                    .getAction();
+            // 如果捕捉到的action是ACTION_BATTERY_CHANGED
+
+            if (RABroadcast.ACTION_UPLOAD_ADD_TASK.equals(action)) {
+
+                ArrayList<Bundle> tasks = intent.getParcelableArrayListExtra("tasks");
+
+
+                uploadManager.addTasks(tasks);
+            }
+//            else if ("REDANT.RAImage.SAVE_TASK".equals(action)) {
+//                uploadManager.stopAllTasks();
+//            }
+            else if (intent
+                    .getAction()
+                    .equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
+
+                ConnectivityManager connManager = (ConnectivityManager) context
+                        .getSystemService(Context.CONNECTIVITY_SERVICE);
+
+                NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
+                if (networkInfo == null) {
+                    dbgUtil.Logd(
+                            "Current Network info",
+                            "can not get Active NetworkInfo!");
+                    return;
+                }
+                NetworkInfo.State netState = networkInfo
+                        .getState();
+                if (netState != NetworkInfo.State.CONNECTED) {
+                    dbgUtil.Logd(
+                            "Current Network info",
+                            "not Connected!State="
+                                    + netState);
+                    return;
+                } else {
+
+                    int iconntype = -1;
+                    iconntype = networkInfo
+                            .getType();
+                    SharedPreferences pref =
+                            getSharedPreferences(
+                                    "UploadManager",
+                                    0);
+
+
+                    boolean
+                            wifi_only
+                            = pref.getBoolean("wifi_only",
+                            false);
+
+                    if
+                            (wifi_only
+                            == true
+                            && iconntype !=
+                            ConnectivityManager.TYPE_WIFI
+                            && iconntype !=
+                            9/* earthnet */) {
+                        uploadManager.stopAllTasks();
+//															 dbgUtil.Log(Log.DEBUG,
+//															 "Current Network info",
+//															 "not allowed!Connection type="
+//															 +
+//															 networkInfo.getTypeName());
+                        return;
+                    }
+                }
+
+
+            } else if (RABroadcast.ACTION_LOCATION_ENABLE_TRACING
+                    .equals(action)) {
+                enable_locationTracing(locationTracing_timeInterval, locationTracing_distance);
+            } else if (RABroadcast.ACTION_LOCATION_DISABLE_TRACING
+                    .equals(action)) {
+
+                disable_locationTracing();
+            } else if (RABroadcast.ACTION_LOCATION_REQUEST_LOCATION
+                    .equals(action)) {
+
+
+                String receiverID=intent.getStringExtra("receiverID");
+//                locationManager.requestSingleUpdate();
+                request_location(receiverID);
+//                locationCallback.onLocationChanged();
+            }
+            else if (RABroadcast.ACTION_PUSHNOTIFICATION_CHECK
+                    .equals(action))
+            {
+                checkpush(context);
+            }
+            else if (RABroadcast.ACTION_PUSHNOTIFICATION_ENABLE_CHECK
+                    .equals(action))
+            {
+
+                String tag = "onReceive@Alarmreceiver";
+//                Log.i( tag, "receive alarm broadcast caller =="
+//                        + intent.getStringExtra("caller"));
+
+                startalarm();
+
+//                checkpush(context);
+
+//                if (SystemClock.elapsedRealtime()
+//                        - ApexTrackingApplication.getLastCheckMessageTime() > 120000)
+//                {
+//                    Log.i(tag, "check messsage");
+//                    ApexTrackingApplication.UpdateLastCheckMessageTime();
+//                    checkpush(context);
+//
+//                }
+            }
+            else if (RABroadcast.ACTION_PUSHNOTIFICATION_DISABLE_CHECK
+                    .equals(action))
+            {
+                if (m_task != null)
+                    m_task.cancel(true);
+//                NotificationManager nManager = (NotificationManager) context
+//                        .getSystemService(Context.NOTIFICATION_SERVICE);
+//                nManager.cancel(R.layout.activity_apex);
+                cancelalarm();
+                // ApexTrackingApplication.put_password("");
+                // ApexTrackingApplication.put_sessionid("");
+                // ApexTrackingApplication.put_user("");
+//                ApexTrackingApplication.logout();
+            }
+        }
+    };
+
+    public static AppImpl getInstance() {
+        return mApp;
+    }
+    @Override
+    public void onCreate() {
+        Log.d("Apex Driver", "ApexDriverApplication onCreate: ");
+        super.onCreate();
+
+        mApp = this;
+
+
+
+        Setup();
+
+        msgFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
+
+        if ((service_flag & FLAG_MODULE_UPLOAD) == FLAG_MODULE_UPLOAD) {
+            uploadManager = new RAUploadManager(getApplicationContext());
+//            msgFilter.addAction("REDANT.POP.RESET_LOCATION");
+//            msgFilter.addAction("REDANT.POP.QUERY_UPLOAD_STATE");
+            msgFilter.addAction("REDANT.BROADCAST.ACTION_UPLOAD_ADD_TASK");
+//            msgFilter.addAction("REDANT.BROADCAST.UPLOAD_MODIFY_QUEUE");
+//            msgFilter.addAction("REDANT.BROADCAST.UPLOAD_RETRY_UPLOAD");
+        }
+        if ((service_flag & FLAG_MODULE_LOCATION) == FLAG_MODULE_LOCATION) {
+
+
+            msgFilter.addAction(RABroadcast.ACTION_LOCATION_ENABLE_TRACING);
+            msgFilter.addAction(RABroadcast.ACTION_LOCATION_DISABLE_TRACING);
+            msgFilter.addAction(RABroadcast.ACTION_LOCATION_REQUEST_LOCATION);
+//            msgFilter.addAction("REDANT.BROADCAST.RESET_LOCATION");
+            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
+
+            locationListener = new LocationListener() {
+
+                // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
+                @Override
+                public void onStatusChanged(String provider, int status,
+                                            Bundle extras) {
+
+                }
+
+                // Provider被enable时触发此函数,比如GPS被打开
+                @Override
+                public void onProviderEnabled(String provider) {
+
+                }
+
+                // Provider被disable时触发此函数,比如GPS被关闭
+                @Override
+                public void onProviderDisabled(String provider) {
+
+                }
+
+                // 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发
+                @Override
+                public void onLocationChanged(Location location) {
+                    locationCallback.onLocationChanged(location);
+
+                }
+            };
+
+
+            enable_locationTracing(locationTracing_timeInterval, locationTracing_distance);
+
+
+//          msgFilter.addAction("REDANT.POP.GPS_ON");
+//		    msgFilter.addAction("REDANT.POP.GPS_OFF");
+//		    msgFilter.addAction("REDANT.POP.REQUEST_LOCATION");
+        }
+        if ((service_flag & FLAG_MODULE_NOTIFICATION) == FLAG_MODULE_NOTIFICATION) {
+
+            if (TextUtils.isEmpty(url_checknotification)) {
+                Log.e(TAG, "onCreate: setup FLAG_SERVICE_NOTIFICATION without url_checknotification");
+            }
+
+            msgFilter.addAction("REDANT.BROADCAST.ACTION_PUSHNOTIFICATION_CHECK");
+
+        }
+
+        registerReceiver(receiver, msgFilter);
+
+        super.onCreate();
+
+    }
+
+
+    //check push
+    private void startalarm()
+    {
+
+//        SharedPreferences pref = getSharedPreferences("Apex", 0);
+//        boolean autologin = pref.getBoolean("autologin", false);
+//        if (autologin == false)
+//            return;
+
+        // 启动完成
+        Intent iAlarm = new Intent(this, BroadcastReceiver.class);
+//        iAlarm.putExtra("caller", caller);
+        iAlarm.setAction(RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
+        PendingIntent sender = PendingIntent.getBroadcast(this, 0,
+                iAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
+
+        long firstime = SystemClock.elapsedRealtime();
+//		UpdateLastAlermTime();
+        AlarmManager am = (AlarmManager) this.getSystemService(
+                Context.ALARM_SERVICE);
+
+        // 30秒一个周期,不停的发送广播
+        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime,
+                pushcheck_timeInterval, sender);
+    }
+
+    private void cancelalarm()
+    {
+
+        // 启动完成
+        Intent iAlarm = new Intent(this, BroadcastReceiver.class);
+        iAlarm.setAction(RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
+        PendingIntent sender = PendingIntent.getBroadcast(this, 0,
+                iAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
+
+        AlarmManager am = (AlarmManager) getSystemService(
+                Context.ALARM_SERVICE);
+
+        am.cancel(sender);
+    }
+    // location
+    void disable_locationTracing() {
+        locationManager.removeUpdates(locationListener);
+    }
+
+
+    void enable_locationTracing(int timeInterval, int distance ) {
+
+        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+            // TODO: Consider calling
+            //    ActivityCompat#requestPermissions
+            // here to request the missing permissions, and then overriding
+            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
+            //                                          int[] grantResults)
+            // to handle the case where the user grants the permission. See the documentation
+            // for ActivityCompat#requestPermissions for more details.
+            return;
+        }
+
+
+        locationManager.requestLocationUpdates(
+                "fused", timeInterval, distance,
+                locationListener);
+//        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
+//
+//
+//
+//
+//        } else if (locationManager
+//                .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
+//
+//
+//            locationManager.requestLocationUpdates(
+//                    LocationManager.NETWORK_PROVIDER, timeInterval, distance,
+//                    locationListener);
+//
+//        }
+    }
+
+    protected Location request_cachedlocation()
+    {
+        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+
+            return null;
+        }
+
+
+
+        //使用GPS获取上一次的地址,这样获取到的信息需要多次,才能够显示出来,所以后面有动态的判断
+        Location location = locationManager.getLastKnownLocation("fused");
+        return location;
+
+    }
+    protected void request_location(final String receiverID)
+    {
+        if(receiverID==null)
+            throw new IllegalArgumentException("receiverID can't be null");
+
+//        Criteria criteria = new Criteria();
+//        criteria.setAccuracy(Criteria.ACCURACY_COARSE);//低精度,如果设置为高精度,依然获取不了location。
+//        criteria.setAltitudeRequired(false);//不要求海拔
+//        criteria.setBearingRequired(false);//不要求方位
+//        criteria.setCostAllowed(true);//允许有花费
+//        criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
+//
+//        //从可用的位置提供器中,匹配以上标准的最佳提供器
+//        String locationProvider = locationManager.getBestProvider(criteria, true);
+
+
+        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+            // TODO: Consider calling
+            //    ActivityCompat#requestPermissions
+            // here to request the missing permissions, and then overriding
+            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
+            //                                          int[] grantResults)
+            // to handle the case where the user grants the permission. See the documentation
+            // for ActivityCompat#requestPermissions for more details.
+            return ;
+        }
+
+        LocationListener singleListener = new LocationListener() {
+            @Override
+            public void onLocationChanged(Location location) {
+
+                Intent Bintent = new Intent(RABroadcast.EVENT_RETURN_LOCATION);
+                Bintent.putExtra("location",location);
+                Bintent.putExtra("receiverID",receiverID);
+                sendBroadcast(Bintent);
+
+
+
+            }
+
+            @Override
+            public void onStatusChanged(String s, int i, Bundle bundle) {
+
+            }
+
+            @Override
+            public void onProviderEnabled(String s) {
+
+            }
+
+            @Override
+            public void onProviderDisabled(String s) {
+
+            }
+        };
+
+
+        locationManager.requestSingleUpdate("fused", singleListener, null);
+
+
+    }
+}

+ 3 - 0
ApexDrivers/RAUtilsLibrary/src/main/java/com/usai/redant/rautils/Receiver/BootCompleteBroadcastReceiver.java

@@ -3,6 +3,7 @@ package com.usai.redant.rautils.Receiver;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
+import android.util.Log;
 
 import com.usai.redant.rautils.Utils.dbgUtil;
 
@@ -17,6 +18,7 @@ public abstract class BootCompleteBroadcastReceiver extends BroadcastReceiver {
 
         if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
 
+            Log.d("BootComplete", "onReceive: ACTION_BOOT_COMPLETED");
             OnBootComplete(context,intent);
 
 //            dbgUtil.fileLog(context,"RAUtilsLibrary: BootCompleteBroadcastReceiver ACTION_BOOT_COMPLETED redeived");
@@ -41,6 +43,7 @@ public abstract class BootCompleteBroadcastReceiver extends BroadcastReceiver {
 //            ApexTrackingApplication.startalarm("boot completed");
         }
         else if (Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(intent.getAction())) {
+            Log.d("BootComplete", "onReceive: ACTION_LOCKED_BOOT_COMPLETED");
             OnLockedBootComplete(context,intent);
         }
     }

+ 27 - 28
ApexDrivers/RAUtilsLibrary/src/main/java/com/usai/redant/rautils/Receiver/RABroadcastReceiver.java

@@ -3,49 +3,48 @@ package com.usai.redant.rautils.Receiver;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
-import android.text.TextUtils;
 
 import com.usai.redant.rautils.Utils.dbgUtil;
 
 public class RABroadcastReceiver extends BroadcastReceiver {
 
-    PushNotificationCallback notificationCallback=null;
-    private String receiverID = null;
+//    PushNotificationCallback notificationCallback=null;
+//    private String receiverID = null;
 
 
 
-    public RABroadcastReceiver(String receiverID)
-    {
-        if(receiverID==null)
-            throw new IllegalArgumentException("receiverID can't be null");
-        this.receiverID = receiverID;
-    }
-    public void initPushNotificationCallback(PushNotificationCallback notificationCallback)
-    {
-        this.notificationCallback = notificationCallback;
-    }
+//    public RABroadcastReceiver(String receiverID)
+//    {
+//        if(receiverID==null)
+//            throw new IllegalArgumentException("receiverID can't be null");
+//        this.receiverID = receiverID;
+//    }
+//    public void initPushNotificationCallback(PushNotificationCallback notificationCallback)
+//    {
+//        this.notificationCallback = notificationCallback;
+//    }
 
 
     @Override
     public void onReceive(Context context, Intent intent) {
         dbgUtil.fileLog(context,"RABroadcastReceiver: onReceive" + intent.getAction());
 
-        if(!(intent.getStringExtra("receiverID").equals(receiverID)|| TextUtils.isEmpty(intent.getStringExtra("receiverID"))))
-            return;
-        if (RABroadcast.EVENT_PUSHNOTIFICATION.equals(intent.getAction())) {
-            if(notificationCallback!=null)
-                notificationCallback.onPushNotification(intent);
-        }
-        else if (RABroadcast.EVENT_SILENCECOMMAND.equals(intent.getAction())) {
-            if(notificationCallback!=null)
-                notificationCallback.onSilentCommand(intent);
-        }
-    }
-
-    public interface PushNotificationCallback {
-        public abstract void onPushNotification(Intent intent);
-        public abstract void onSilentCommand(Intent intent);
+//        if(!(intent.getStringExtra("receiverID").equals(receiverID)|| TextUtils.isEmpty(intent.getStringExtra("receiverID"))))
+//            return;
+//        if (RABroadcast.EVENT_PUSHNOTIFICATION.equals(intent.getAction())) {
+//            if(notificationCallback!=null)
+//                notificationCallback.onPushNotification(intent);
+//        }
+//        else if (RABroadcast.EVENT_SILENCECOMMAND.equals(intent.getAction())) {
+//            if(notificationCallback!=null)
+//                notificationCallback.onSilentCommand(intent);
+//        }
     }
+//
+//    public interface PushNotificationCallback {
+//        public abstract void onPushNotification(Intent intent);
+//        public abstract void onSilentCommand(Intent intent);
+//    }
 
 
 }

+ 119 - 55
ApexDrivers/RAUtilsLibrary/src/main/java/com/usai/redant/rautils/Service/RAService.java

@@ -3,6 +3,7 @@ package com.usai.redant.rautils.Service;
 import android.Manifest;
 import android.app.AlarmManager;
 import android.app.Notification;
+import android.app.NotificationChannel;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
 import android.app.Service;
@@ -19,15 +20,18 @@ import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.os.AsyncTask;
 import android.os.Binder;
+import android.os.Build;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.os.SystemClock;
 import android.support.v4.app.ActivityCompat;
+import android.support.v4.app.NotificationCompat;
 import android.text.TextUtils;
 import android.util.Log;
 
 import com.usai.redant.rautils.R;
 import com.usai.redant.rautils.Receiver.RABroadcast;
+import com.usai.redant.rautils.Receiver.RABroadcastReceiver;
 import com.usai.redant.rautils.Upload.RAUploadManager;
 import com.usai.redant.rautils.Utils.Network;
 import com.usai.redant.rautils.Utils.dbgUtil;
@@ -37,13 +41,14 @@ import org.json.JSONObject;
 
 import java.util.ArrayList;
 
+//@Deprecated
 public abstract class RAService extends Service {
 
     private static final String TAG = "RAService";
 
     public static final int DEFAULT_LOCATION_TIMEINTERVAL = 60 * 1000;
     public static final int DEFAULT_DISTANCE = 60 * 50;
-    public static final int DEFAULT_PUSHNOTIFICATION_TIMEINTERVAL = 30 * 1000;
+    public static final int DEFAULT_PUSHNOTIFICATION_TIMEINTERVAL = 5 * 1000;
 
     public static final int FLAG_SERVICE_NONE = 0;
     public static final int FLAG_SERVICE_LOCATION = 1 << 1;
@@ -61,6 +66,7 @@ public abstract class RAService extends Service {
     public interface ServiceUpload {
 
     }
+
     public void initServiceUpload(ServiceUpload uploadCallback) {
         service_flag = service_flag | FLAG_SERVICE_UPLOAD;
 //        this.upload = locationCallback;
@@ -83,7 +89,7 @@ public abstract class RAService extends Service {
     public interface ServiceLocation {
 
 
-        public abstract  Location RequestCachedLocation();
+        public abstract Location RequestCachedLocation();
 //        public abstract void RequestLocation_ByBroadcast(String receiverID);
 
         public abstract void onLocationChanged(Location location);
@@ -286,6 +292,8 @@ public abstract class RAService extends Service {
 
     public void checkpush(Context context) {
 
+        if(true)
+        return;
         if (m_task != null) {
             return;
         }
@@ -420,7 +428,7 @@ public abstract class RAService extends Service {
                 Log.e(TAG, "onCreate: setup FLAG_SERVICE_NOTIFICATION without url_checknotification");
             }
 
-            msgFilter.addAction("REDANT.BROADCAST.ACTION_PUSHNOTIFICATION_CHECK");
+            msgFilter.addAction(RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
 
         }
 
@@ -428,6 +436,27 @@ public abstract class RAService extends Service {
 
         super.onCreate();
 
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+            String CHANNEL_ID = "apex & driver";
+            String CHANNEL_NAME = "Background Service";
+
+            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
+                    CHANNEL_NAME, NotificationManager.IMPORTANCE_NONE);
+            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
+
+            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
+                    .setCategory(Notification.CATEGORY_SERVICE).setSmallIcon(R.drawable.ic_launcher_foreground).setPriority(1000).build();
+
+            startForeground(101, notification);
+        }
+
+//        SharedPreferences pref = getSharedPreferences("Apex & Drivers", 0);
+//        boolean notification = pref.getBoolean("enable_notification", false);
+//        notification = true;
+//        if (notification == true)
+            startalarm();
+
+
     }
 
 
@@ -436,13 +465,19 @@ public abstract class RAService extends Service {
         Log.e("_SERVICE", "onDestroy: ");
         if (uploadManager != null)
             uploadManager.saveTasks();
+
+        unregisterReceiver(uploadReceiver);
+        super.onDestroy();
     }
 
-    private BroadcastReceiver uploadReceiver = new BroadcastReceiver() {
+    private BroadcastReceiver uploadReceiver = new RABroadcastReceiver() {
 
         public void onReceive(Context context, Intent intent) {
             String action = intent
                     .getAction();
+
+            Log.d(TAG, "onReceive: " + action);
+            dbgUtil.fileLog(context,TAG+"   RABroadcastReceiver: onReceive  " + action);
             // 如果捕捉到的action是ACTION_BATTERY_CHANGED
 
             if (RABroadcast.ACTION_UPLOAD_ADD_TASK.equals(action)) {
@@ -488,18 +523,9 @@ public abstract class RAService extends Service {
                                     0);
 
 
-                    boolean
-                            wifi_only
-                            = pref.getBoolean("wifi_only",
-                            false);
+                    boolean wifi_only = pref.getBoolean("wifi_only", false);
 
-                    if
-                            (wifi_only
-                            == true
-                            && iconntype !=
-                            ConnectivityManager.TYPE_WIFI
-                            && iconntype !=
-                            9/* earthnet */) {
+                    if (wifi_only == true && iconntype != ConnectivityManager.TYPE_WIFI && iconntype != 9/* earthnet */) {
                         uploadManager.stopAllTasks();
 //															 dbgUtil.Log(Log.DEBUG,
 //															 "Current Network info",
@@ -511,8 +537,7 @@ public abstract class RAService extends Service {
                 }
 
 
-            } else if (RABroadcast.ACTION_LOCATION_ENABLE_TRACING
-                    .equals(action)) {
+            } else if (RABroadcast.ACTION_LOCATION_ENABLE_TRACING.equals(action)) {
                 enable_locationTracing(locationTracing_timeInterval, locationTracing_distance);
             } else if (RABroadcast.ACTION_LOCATION_DISABLE_TRACING
                     .equals(action)) {
@@ -522,19 +547,37 @@ public abstract class RAService extends Service {
                     .equals(action)) {
 
 
-                String receiverID=intent.getStringExtra("receiverID");
+                String receiverID = intent.getStringExtra("receiverID");
 //                locationManager.requestSingleUpdate();
                 request_location(receiverID);
 //                locationCallback.onLocationChanged();
-            }
-            else if (RABroadcast.ACTION_PUSHNOTIFICATION_CHECK
-                    .equals(action))
-            {
+            } else if (RABroadcast.ACTION_PUSHNOTIFICATION_CHECK.equals(action)) {
+
+                // 重复定时任务
+
+//                Intent iAlarm = new Intent(RAService.this, RABroadcastReceiver.class);
+//        iAlarm.putExtra("caller", caller);
+                Intent iAlarm = new Intent(RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
+//                iAlarm.setAction(RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
+                PendingIntent sender = PendingIntent.getBroadcast(RAService.this, 0,
+                        iAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
+
+
+
+                AlarmManager am = (AlarmManager) RAService.this.getSystemService(
+                        Context.ALARM_SERVICE);
+
+
+                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+                    am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + pushcheck_timeInterval, sender);
+                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+                    am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + pushcheck_timeInterval, sender);
+                }
+
+//                Log.d(TAG, "onReceive: " + RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
                 checkpush(context);
-            }
-            else if (RABroadcast.ACTION_PUSHNOTIFICATION_ENABLE_CHECK
-                    .equals(action))
-            {
+            } else if (RABroadcast.ACTION_PUSHNOTIFICATION_ENABLE_CHECK
+                    .equals(action)) {
 
                 String tag = "onReceive@Alarmreceiver";
 //                Log.i( tag, "receive alarm broadcast caller =="
@@ -552,10 +595,8 @@ public abstract class RAService extends Service {
 //                    checkpush(context);
 //
 //                }
-            }
-            else if (RABroadcast.ACTION_PUSHNOTIFICATION_DISABLE_CHECK
-                    .equals(action))
-            {
+            } else if (RABroadcast.ACTION_PUSHNOTIFICATION_DISABLE_CHECK
+                    .equals(action)) {
                 if (m_task != null)
                     m_task.cancel(true);
 //                NotificationManager nManager = (NotificationManager) context
@@ -569,18 +610,18 @@ public abstract class RAService extends Service {
             }
         }
     };
+
     private void startalarm()
+
     {
+        Log.d(TAG, "startalarm: ");
 
-//        SharedPreferences pref = getSharedPreferences("Apex", 0);
-//        boolean autologin = pref.getBoolean("autologin", false);
-//        if (autologin == false)
-//            return;
 
         // 启动完成
-        Intent iAlarm = new Intent(this, BroadcastReceiver.class);
+//        Intent iAlarm = new Intent(this, RABroadcastReceiver.class);
 //        iAlarm.putExtra("caller", caller);
-        iAlarm.setAction(RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
+        Intent iAlarm = new Intent(RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
+//        iAlarm.setAction(RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
         PendingIntent sender = PendingIntent.getBroadcast(this, 0,
                 iAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
 
@@ -589,16 +630,34 @@ public abstract class RAService extends Service {
         AlarmManager am = (AlarmManager) this.getSystemService(
                 Context.ALARM_SERVICE);
 
-        // 30秒一个周期,不停的发送广播
-        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime,
-                pushcheck_timeInterval, sender);
+//        // 30秒一个周期,不停的发送广播
+//        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime,
+//                pushcheck_timeInterval, sender);
+
+
+
+
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+            am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), sender);
+        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+            am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), sender);
+        } else {
+            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), pushcheck_timeInterval, sender);
+        }
+
+//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
+//            am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), sender);
+//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+//            am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), sender);
+//        } else {
+//            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), pushcheck_timeInterval, sender);
+//        }
     }
 
-    private void cancelalarm()
-    {
+    private void cancelalarm() {
 
         // 启动完成
-        Intent iAlarm = new Intent(this, BroadcastReceiver.class);
+        Intent iAlarm = new Intent(this, RABroadcastReceiver.class);
         iAlarm.setAction(RABroadcast.ACTION_PUSHNOTIFICATION_CHECK);
         PendingIntent sender = PendingIntent.getBroadcast(this, 0,
                 iAlarm, PendingIntent.FLAG_UPDATE_CURRENT);
@@ -607,18 +666,26 @@ public abstract class RAService extends Service {
                 Context.ALARM_SERVICE);
 
         am.cancel(sender);
-    }
-    void registerReceiver() {
+//        SharedPreferences pref = getSharedPreferences("Apex & Drivers", 0);
+//        SharedPreferences.Editor editor = pref.edit();
+//
+//        editor.putBoolean("enable_notification", false);
+//        editor.commit();
+
 
     }
 
+//    void registerReceiver() {
+//
+//    }
+
 
     void disable_locationTracing() {
         locationManager.removeUpdates(locationListener);
     }
 
 
-    void enable_locationTracing(int timeInterval, int distance ) {
+    void enable_locationTracing(int timeInterval, int distance) {
 
         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
             // TODO: Consider calling
@@ -651,23 +718,21 @@ public abstract class RAService extends Service {
 //        }
     }
 
-    protected Location request_cachedlocation()
-    {
+    protected Location request_cachedlocation() {
         if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
 
             return null;
         }
 
 
-
         //使用GPS获取上一次的地址,这样获取到的信息需要多次,才能够显示出来,所以后面有动态的判断
         Location location = locationManager.getLastKnownLocation("fused");
         return location;
 
     }
-    protected void request_location(final String receiverID)
-    {
-        if(receiverID==null)
+
+    protected void request_location(final String receiverID) {
+        if (receiverID == null)
             throw new IllegalArgumentException("receiverID can't be null");
 
 //        Criteria criteria = new Criteria();
@@ -689,7 +754,7 @@ public abstract class RAService extends Service {
             //                                          int[] grantResults)
             // to handle the case where the user grants the permission. See the documentation
             // for ActivityCompat#requestPermissions for more details.
-            return ;
+            return;
         }
 
         LocationListener singleListener = new LocationListener() {
@@ -697,12 +762,11 @@ public abstract class RAService extends Service {
             public void onLocationChanged(Location location) {
 
                 Intent Bintent = new Intent(RABroadcast.EVENT_RETURN_LOCATION);
-                Bintent.putExtra("location",location);
-                Bintent.putExtra("receiverID",receiverID);
+                Bintent.putExtra("location", location);
+                Bintent.putExtra("receiverID", receiverID);
                 sendBroadcast(Bintent);
 
 
-
             }
 
             @Override

+ 74 - 88
ApexDrivers/RAUtilsLibrary/src/main/java/com/usai/redant/rautils/Utils/RAUtil.java

@@ -8,6 +8,7 @@ import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.os.Build;
 import android.os.Bundle;
+import android.provider.Settings;
 import android.support.v4.app.ActivityCompat;
 import android.support.v4.content.PermissionChecker;
 import android.telephony.TelephonyManager;
@@ -31,14 +32,14 @@ import java.util.UUID;
 import java.util.concurrent.atomic.AtomicInteger;
 
 public class RAUtil {
-    public static void LibTest1()
-    {
-        dbgUtil.Logd("RAUtilsLibrary","LibTest1 aar update successful");
+    public static void LibTest1() {
+        dbgUtil.Logd("RAUtilsLibrary", "LibTest1 aar update successful");
     }
-    public static void LibTest()
-    {
-        dbgUtil.Logd("RAUtilsLibrary","LibTest aar update successful");
+
+    public static void LibTest() {
+        dbgUtil.Logd("RAUtilsLibrary", "LibTest aar update successful");
     }
+
     public static String getApplicationName(Context context) {
 
         PackageManager packageManager = null;
@@ -53,26 +54,25 @@ public class RAUtil {
         return applicationName;
     }
 
-    public static boolean isNumeric(String str){
-        for (int i = 0; i < str.length(); i++){
+    public static boolean isNumeric(String str) {
+        for (int i = 0; i < str.length(); i++) {
             System.out.println(str.charAt(i));
-            if (!Character.isDigit(str.charAt(i))){
+            if (!Character.isDigit(str.charAt(i))) {
                 return false;
             }
         }
         return true;
     }
 
-    public static JSONObject Bundle2Json(Bundle bundle)
-    {
+    public static JSONObject Bundle2Json(Bundle bundle) {
         JSONObject json = new JSONObject();
         Set<String> keys = bundle.keySet();
         for (String key : keys) {
             try {
-                Log.d("", "Bundle2Json: key:"+key+"  val: "+wrap(bundle.get(key)));
+                Log.d("", "Bundle2Json: key:" + key + "  val: " + wrap(bundle.get(key)));
                 json.put(key, wrap(bundle.get(key))); //see edit below
 //                json.put(key, JSONObject.wrap(bundle.get(key)));
-            } catch(JSONException e) {
+            } catch (JSONException e) {
                 //Handle exception here
             }
         }
@@ -90,8 +90,7 @@ public class RAUtil {
             return o;
         }
         try {
-            if (o instanceof Bundle)
-            {
+            if (o instanceof Bundle) {
                 return Bundle2Json((Bundle) o);
 
             }
@@ -133,6 +132,7 @@ public class RAUtil {
         }
         return result;
     }
+
     public static Bundle Json2Bundle(JSONObject s) {
         Bundle bundle = new Bundle();
 
@@ -142,54 +142,31 @@ public class RAUtil {
                 Object o = s.get(key);
 
 
-
                 if (o == null) {
                     continue;
-                }
-                else if ( o instanceof JSONObject) {
-                    bundle.putBundle(key,Json2Bundle((JSONObject) o));
-                }
-                else if(o instanceof JSONArray)
-                {
+                } else if (o instanceof JSONObject) {
+                    bundle.putBundle(key, Json2Bundle((JSONObject) o));
+                } else if (o instanceof JSONArray) {
                     throw new JSONException("Json2Bundle does not support Json array: " + o.getClass());// bundle.putarr
-                }
-                else if (o.equals(JSONObject.NULL)) {
+                } else if (o.equals(JSONObject.NULL)) {
                     continue;
-                }
-                else if (o instanceof Boolean)
-                {
-                    bundle.putBoolean(key,((Boolean) o).booleanValue());
-                }
-                else if(o instanceof Byte)
-                {
+                } else if (o instanceof Boolean) {
+                    bundle.putBoolean(key, ((Boolean) o).booleanValue());
+                } else if (o instanceof Byte) {
                     bundle.putByte(key, ((Byte) o).byteValue());
-                }
-                else if(o instanceof Character)
-                {
+                } else if (o instanceof Character) {
                     bundle.putChar(key, ((Character) o).charValue());
-                }
-                else if(o instanceof Double)
-                {
+                } else if (o instanceof Double) {
                     bundle.putDouble(key, ((Double) o).doubleValue());
-                }
-                else if(o instanceof Float)
-                {
+                } else if (o instanceof Float) {
                     bundle.putFloat(key, ((Float) o).floatValue());
-                }
-                else if(o instanceof Integer)
-                {
+                } else if (o instanceof Integer) {
                     bundle.putInt(key, ((Integer) o).intValue());
-                }
-                else if(o instanceof Long)
-                {
+                } else if (o instanceof Long) {
                     bundle.putLong(key, ((Long) o).longValue());
-                }
-                else if(o instanceof Short)
-                {
+                } else if (o instanceof Short) {
                     bundle.putShort(key, ((Short) o).shortValue());
-                }
-                else if(o instanceof String)
-                {
+                } else if (o instanceof String) {
                     bundle.putString(key, o.toString());
                 }
 
@@ -199,7 +176,6 @@ public class RAUtil {
 //                bundle.putParcelableArrayList("arr", a);
 
 
-
             } catch (JSONException e) {
                 e.printStackTrace();
             }
@@ -208,37 +184,32 @@ public class RAUtil {
     }
 
 
-    public static final int MY_PERMISSIONS_REQUEST= 1;
+    public static final int MY_PERMISSIONS_REQUEST = 1;
 
-    public static Boolean checkPermissions(Activity activity, String[] permissions)
-    {
-        if (Build.VERSION.SDK_INT >= 23)
-        {
-            return checkPermissions_23(activity,permissions);
-        }
-        else
-        {
+    public static Boolean checkPermissions(Activity activity, String[] permissions) {
+        if (Build.VERSION.SDK_INT >= 23) {
+            return checkPermissions_23(activity, permissions);
+        } else {
             return false;
         }
     }
 
-    public static Boolean checkPermissions_23(Activity activity, String[] permissions)
-    {
+    public static Boolean checkPermissions_23(Activity activity, String[] permissions) {
         Log.d("_RAIMAGE", "checkPermissions23:==================================== ");
 
         ArrayList<String> request_list = new ArrayList<String>();
-        for(String permission : permissions) {
-            boolean bshow= ActivityCompat.shouldShowRequestPermissionRationale(activity,permission);
+        for (String permission : permissions) {
+            boolean bshow = ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
 
-            boolean pc = PermissionChecker.checkSelfPermission(activity,permission)== PermissionChecker.PERMISSION_GRANTED;
+            boolean pc = PermissionChecker.checkSelfPermission(activity, permission) == PermissionChecker.PERMISSION_GRANTED;
 
-            if(!pc)
+            if (!pc)
                 request_list.add(permission);
         }
         Log.d("_RAIMAGE", "checkPermissions23:==================================== ");
 
 
-        if(request_list.isEmpty())
+        if (request_list.isEmpty())
             return false;
         ActivityCompat.requestPermissions(activity, request_list.toArray(new String[0]), MY_PERMISSIONS_REQUEST);
 
@@ -247,8 +218,7 @@ public class RAUtil {
 
     }
 
-    public static Boolean checkPermissions_23(Context applicationContext, String[] permissions)
-    {
+    public static Boolean checkPermissions_23(Context applicationContext, String[] permissions) {
         if (applicationContext == null) {
             return false;
         }
@@ -256,12 +226,12 @@ public class RAUtil {
 
         ArrayList<String> request_list = new ArrayList<String>();
         Context context = applicationContext;
-        for(String permission : permissions) {
+        for (String permission : permissions) {
 
-            boolean pc = PermissionChecker.checkSelfPermission(context,permission)== PermissionChecker.PERMISSION_GRANTED;
-            if(!pc) {
+            boolean pc = PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED;
+            if (!pc) {
                 Log.d("RAUtilsLibrary", "checkPermissions23:==================================== ");
-                Log.d("RAUtilsLibrary", "checkPermissions23: permission"+ permission +" denied");
+                Log.d("RAUtilsLibrary", "checkPermissions23: permission" + permission + " denied");
                 Log.d("RAUtilsLibrary", "checkPermissions23:==================================== ");
                 return false;
             }
@@ -269,15 +239,13 @@ public class RAUtil {
 //        Log.d("RAUtilsLibrary", "checkPermissions23:==================================== ");
 
 
-
         return true;
 
     }
 
-    public static Boolean checkPermissions_24(Activity activity, String[] permissions)
-    {
+    public static Boolean checkPermissions_24(Activity activity, String[] permissions) {
 
-        if(permissions.length==0)
+        if (permissions.length == 0)
             return true;
         ActivityCompat.requestPermissions(activity, permissions, MY_PERMISSIONS_REQUEST);
 
@@ -285,7 +253,7 @@ public class RAUtil {
         return true;
     }
 
-    public static int iconName2Rid(Context context,String name) {
+    public static int iconName2Rid(Context context, String name) {
 
         if (context == null) {
             return 0;
@@ -301,8 +269,9 @@ public class RAUtil {
     }
 
     private static final AtomicInteger sNextGeneratedId = new AtomicInteger(1);
+
     /**
-     * Generate a value suitable for use in {@link #setId(int)}.
+
      * This value will not collide with ID values generated at build time by aapt for R.id.
      *
      * @return a generated ID value
@@ -341,15 +310,13 @@ public class RAUtil {
             }
             tmDevice = "" + tm.getDeviceId();
             tmSerial = "" + tm.getSimSerialNumber();
-            androidId = "" + android.provider.Settings.Secure.getString(application.getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);
-            UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
+            androidId = "" + android.provider.Settings.Secure.getString(application.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
+            UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
             uniqueId = deviceUuid.toString();
-            Log.d("debug","uuid="+uniqueId);
+            Log.d("debug", "uuid=" + uniqueId);
 
-        }
-        catch(Exception e)
-        {
-            uniqueId= null;
+        } catch (Exception e) {
+            uniqueId = null;
         }
         return uniqueId;
     }
@@ -374,6 +341,25 @@ public class RAUtil {
         return (int) (spValue * fontScale + 0.5f);
     }
 
+
+    public static String getDeviceId(Context context) {
+        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
+        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
+            // TODO: Consider calling
+            //    ActivityCompat#requestPermissions
+            // here to request the missing permissions, and then overriding
+            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
+            //                                          int[] grantResults)
+            // to handle the case where the user grants the permission. See the documentation
+            // for ActivityCompat#requestPermissions for more details.
+            return "";
+        }
+        String deviceId = telephonyManager.getDeviceId().toString();
+        return deviceId;
+    }
+    public static String getAndroidId(Context context) {
+        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
+    }
     public static String stringToMD5(String string) {
         byte[] hash;
 

+ 10 - 4
ApexDrivers/RAUtilsLibrary/src/main/java/com/usai/redant/rautils/Utils/dbgUtil.java

@@ -57,9 +57,10 @@ public class dbgUtil
 
 		boolean result= RAUtil.checkPermissions_23(appContext, permissions);
 
-		if(!result)
+		if(!result) {
+			Log.d("Apex Drivers", "fileLog: no external storage permission");
 			return;
-		
+		}
 		File dir = new File(Environment.getExternalStorageDirectory().getPath()
 				+ "/redant/pop");
 		if (!dir.exists())
@@ -72,8 +73,11 @@ public class dbgUtil
 				.getTimeInMillis());
 
 		File[] f = dir.listFiles();
-		if(f==null)
-		    return;
+		if(f==null) {
+			Log.d("Apex Drivers", "fileLog: list file failed");
+			Log.d("Apex Drivers", Environment.getExternalStorageDirectory().getPath());
+			return;
+		}
 		for (int i = 0; i < f.length; i++)
 		{
 			if(!f[i].isFile())
@@ -134,6 +138,7 @@ public class dbgUtil
 
 		try
 		{
+			Log.d("Apex Drivers", "fileLog: begin write "+ content);
 			loglock.writeLock().lock();
 
 			fw = new FileWriter(Environment.getExternalStorageDirectory()
@@ -147,6 +152,7 @@ public class dbgUtil
 			bw.flush(); // 刷新该流的缓冲
 			bw.close();
 			fw.close();
+			Log.d("Apex Drivers", "fileLog: end write");
 
 		}
 		catch (IOException e)

+ 8 - 9
ApexDrivers/app/app.iml

@@ -70,13 +70,6 @@
       <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/src/main/shaders" isTestSource="false" />
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
-      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
       <sourceFolder url="file://$MODULE_DIR$/src/test/res" type="java-test-resource" />
       <sourceFolder url="file://$MODULE_DIR$/src/test/resources" type="java-test-resource" />
       <sourceFolder url="file://$MODULE_DIR$/src/test/assets" type="java-test-resource" />
@@ -84,6 +77,13 @@
       <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
       <sourceFolder url="file://$MODULE_DIR$/src/test/rs" isTestSource="true" />
       <sourceFolder url="file://$MODULE_DIR$/src/test/shaders" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/shaders" isTestSource="true" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/blame" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/check-manifest" />
@@ -91,7 +91,6 @@
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaPrecompile" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" />
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/prebuild" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
@@ -124,7 +123,6 @@
     <orderEntry type="library" name="Gradle: com.android.support.constraint:constraint-layout-1.1.2" level="project" />
     <orderEntry type="library" name="Gradle: com.android.support:support-core-utils-27.1.1" level="project" />
     <orderEntry type="library" name="Gradle: com.google.android.gms:play-services-basement-11.4.2" level="project" />
-    <orderEntry type="library" name="Gradle: __local_aars__:/Users/macmini1/android project/ApexDrivers/app/libs/core-2.3.0.jar:unspecified@jar" level="project" />
     <orderEntry type="library" scope="TEST" name="Gradle: com.google.code.findbugs:jsr305:2.0.1@jar" level="project" />
     <orderEntry type="library" scope="TEST" name="Gradle: com.android.support.test.espresso:espresso-core-3.0.2" level="project" />
     <orderEntry type="library" scope="TEST" name="Gradle: javax.inject:javax.inject:1@jar" level="project" />
@@ -148,6 +146,7 @@
     <orderEntry type="library" name="Gradle: com.google.android.gms:play-services-maps-11.4.2" level="project" />
     <orderEntry type="library" name="Gradle: com.google.android.gms:play-services-tasks-11.4.2" level="project" />
     <orderEntry type="library" scope="TEST" name="Gradle: net.sf.kxml:kxml2:2.3.0@jar" level="project" />
+    <orderEntry type="library" name="Gradle: __local_aars__:/Users/ray/Documents/code_ERPSuiteAndroid/ApexDrivers/app/libs/core-2.3.0.jar:unspecified@jar" level="project" />
     <orderEntry type="library" name="Gradle: android.arch.lifecycle:runtime-1.1.0" level="project" />
     <orderEntry type="module" module-name="RAUtilsLibrary" />
   </component>

+ 4 - 2
ApexDrivers/app/build.gradle

@@ -4,8 +4,10 @@ android {
     compileSdkVersion 27
     defaultConfig {
         applicationId "com.usai.redant.apexdrivers"
-        minSdkVersion 24
-        targetSdkVersion 27
+
+        minSdkVersion 21
+        targetSdkVersion 26
+
         versionCode 1
         versionName "1.0"
         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

+ 12 - 2
ApexDrivers/app/src/main/AndroidManifest.xml

@@ -6,7 +6,10 @@
     <!-- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> -->
     <!-- <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> -->
 
-    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
+    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
+
+    <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
+
     <uses-permission android:name="android.permission.CAMERA"/>
     <uses-permission android:name="android.permission.WAKE_LOCK"/>
     <uses-permission android:name="android.permission.VIBRATE"/>
@@ -50,8 +53,15 @@
 
         <service
             android:name=".ApexDriversBackgroundService"
+            android:label="ApexDrivers background service"
             android:enabled="true"
-            android:exported="true"/>
+
+            android:exported="true">
+        <!--<intent-filter>-->
+            <!--<action android:name="com.usai.redant.apexdrivers.ApexDriversBackgroundService"/>-->
+        <!--</intent-filter>-->
+    </service>
+
 
         <receiver
             android:name=".Receiver.ApexDriverBootCompleteReceiver"

+ 12 - 4
ApexDrivers/app/src/main/java/com/usai/redant/apexdrivers/ApexDriverApplication.java

@@ -7,6 +7,7 @@ import android.content.Intent;
 import android.content.ServiceConnection;
 import android.content.SharedPreferences;
 import android.location.Location;
+import android.os.Build;
 import android.os.IBinder;
 
 import com.usai.redant.apexdrivers.Utils.OperationQueue;
@@ -52,10 +53,17 @@ public class ApexDriverApplication extends Application {
                 mService = null;
             }
         };
-
-//        Intent serviceintent = new Intent();
-//        serviceintent.setClass(this, ApexDriversBackgroundService.class);
-//        startService(serviceintent);
+//
+        Intent serviceintent = new Intent();
+        serviceintent.setClass(this, ApexDriversBackgroundService.class);
+
+        ComponentName cn ;
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+            cn =this.startForegroundService(serviceintent);
+        } else
+        {
+            cn =this.startService(serviceintent);
+        }
 
 
         Intent intent = new Intent(getApplicationContext(),ApexDriversBackgroundService.class);

+ 28 - 0
ApexDrivers/app/src/main/java/com/usai/redant/apexdrivers/MainActivity.java

@@ -7,8 +7,12 @@ import android.content.Context;
 import android.content.Intent;
 import android.content.ServiceConnection;
 import android.location.Location;
+import android.net.Uri;
+import android.os.Build;
 import android.os.Bundle;
 import android.os.IBinder;
+import android.os.PowerManager;
+import android.provider.Settings;
 import android.support.v4.app.Fragment;
 import android.support.v4.app.FragmentManager;
 import android.support.v4.app.FragmentTransaction;
@@ -112,8 +116,32 @@ public class MainActivity extends AppCompatActivity implements LoginFragment.Log
 
         initView();
 
+//        checkPowerManagement();
+
         Test();
     }
+    void checkPowerManagement()
+    {
+        Intent intent = new Intent();
+        String packageName = getPackageName();
+        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
+
+        if (Build.VERSION.SDK_INT >= 23)
+        {
+            if (!pm.isIgnoringBatteryOptimizations(packageName))
+            {
+                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
+                intent.setData(Uri.parse("package:" + packageName));
+            }
+//                intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
+//            else {
+//                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
+//                intent.setData(Uri.parse("package:" + packageName));
+//            }
+            startActivity(intent);
+
+        }
+    }
 
     private void initView() {
 

+ 19 - 2
ApexDrivers/app/src/main/java/com/usai/redant/apexdrivers/Receiver/ApexDriverBootCompleteReceiver.java

@@ -1,7 +1,9 @@
 package com.usai.redant.apexdrivers.Receiver;
 
+import android.content.ComponentName;
 import android.content.Context;
 import android.content.Intent;
+import android.os.Build;
 import android.util.Log;
 
 import com.usai.redant.apexdrivers.ApexDriversBackgroundService;
@@ -31,13 +33,21 @@ public class ApexDriverBootCompleteReceiver extends BootCompleteBroadcastReceive
 			if (intent.getExtras() != null)
 				intentservice.putExtras(intent.getExtras());
 			intentservice.setAction(intent.getAction());
+//			context.startService(intentservice);
+
+
+		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+			context.startForegroundService(intentservice);
+		} else
+			{
 			context.startService(intentservice);
+		}
 
     }
 
 	@Override
 	protected void OnLockedBootComplete(Context context, Intent intent) {
-		Log.d("ApexDriver", "OnBootComplete: ");
+		Log.d("ApexDriver", "OnLockedBootComplete: ");
 
 
 		dbgUtil.fileLog(context,"ApexDriver: OnLockedBootComplete");
@@ -49,6 +59,13 @@ public class ApexDriverBootCompleteReceiver extends BootCompleteBroadcastReceive
 		if (intent.getExtras() != null)
 			intentservice.putExtras(intent.getExtras());
 		intentservice.setAction(intent.getAction());
-		context.startService(intentservice);
+		ComponentName cn ;
+		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+            cn =context.startForegroundService(intentservice);
+		} else
+        {
+            cn =context.startService(intentservice);
+        }
+		Log.d("ApexDriver", "startservice: "+cn);
 	}
 }

+ 0 - 1
RA Image/app/app.iml

@@ -91,7 +91,6 @@
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaPrecompile" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jniLibs" />
-      <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/prebuild" />
       <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />