如何在电池上保持Android中的后台服务活着?

时间:2016-03-03 11:35:55

标签: android cordova ionic-framework geolocation

我正在构建一个Ionic / Cordova应用程序,它将每4分钟将用户的GPS位置轮询到我的后端服务器。为了实现我的逻辑,我正在使用BGS Core plugin

为了防止CPU睡眠,我实施了一个WakeLock,可以非常快速地耗尽电池电量。理想情况下,我想使用报警管理器或更好的解决方案,但我无法理解如何在MyService插件类的范围内使用报警管理器。

这是我的代码:

    public class MyService extends BackgroundService {

    private final static String TAG = MyService.class.getSimpleName();  
    private String proId = "0";
    private String proIdFromStorage = "";
    private String requestResult = "";

    private String lat = "";
    private String lon = "";
    private String time = "";
    private String locationProvider = "";       

    private String testId = "10";

    private final String device = Build.MODEL;
    private final String manufacturer = Build.MANUFACTURER;
    private final String buildNumber = Build.VERSION.RELEASE;

    private String batteryLevel = "";
    private String isBatteryCharging = "";

    private String isConnnectedToNetwork = "false";
    private String networkType = "Unknown";
    private String imei = "";
    private String imsi = "";   
    private String simSerialNumber = "";
    private String carrier = "";    

    private PowerManager.WakeLock wl = null;

    //Initializing the file name that will store the pro details
    public static final String PRO_DATA_STORE = "ProDataStore"; 

    @Override
    protected JSONObject doWork() {                                         

        requestLocationUpdate(); //It will force phone to get latest location
        performStorageOperations(); //Getting and setting pro id to/from storage        
        setBatteryStats();  //Setting battery stats
        getNetworkInfo(); //Getting and setting network info details
        getLocationInfo(); //Getting and setting location info details
        makeRequestToServer(); //Sending Pro details to Mr Right Server         

        JSONObject result = new JSONObject();
        try { result.put("Message", this.requestResult); } catch (JSONException e) {}   

        return result;  
    }

    @Override
    protected JSONObject getConfig() {

        JSONObject gC = new JSONObject();

        try{            
            gC.put("ProIdFromGet", this.proId);         
        }
        catch (JSONException e) {
        //some exception handler code.
        }               
        return gC;
    }

    @Override
    protected void setConfig(JSONObject config) {           
        try {
            if (config.has("proId"))
            {
                this.proId = config.getString("proId");
            }                                               

        } catch (JSONException e) {
        }

    }               

    @Override
    protected void onTimerEnabled() {
        // TODO Auto-generated method stub
        wakeLockEnable();               
    }

    @Override
    protected void onTimerDisabled() {
        // TODO Auto-generated method stub
        releaseWakeLock();      
    }           

    private void getLocationInfo(){     
        try {
             LocationManager lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);          
             Log.d(TAG, "Location Manager is initilaised"); 
             /*
             Criteria criteria = new Criteria();
             criteria.setAccuracy(Criteria.ACCURACY_FINE);
             criteria.setAltitudeRequired(false);
             criteria.setBearingRequired(false);
             criteria.setCostAllowed(true);
             String strLocationProvider = lm.getBestProvider(criteria, true);
             Log.d(TAG, "Location Provider : " + strLocationProvider);
             */                                         

             try{
                    Location location = null;
                    Location locationGPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    Location locationNetwork = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if(locationGPS != null && locationNetwork != null)
                    {
                        //Testing if GPS Location is not older than 10 mins as compared to Network Location
                        if(locationGPS.getTime() - locationNetwork.getTime() > 8 * 60 * 1000)
                        {
                            location = locationNetwork;
                        }
                        else{
                            location = locationGPS;
                        }
                    }
                    if(locationGPS == null && locationNetwork != null)
                    {
                        location = locationNetwork;
                    }                                                                                                                                           
                    if(location != null)
                    {                                       
                        Log.d(TAG, "Location Fetched Successfully");                        

                        Double lat = location.getLatitude();
                        Double lon = location.getLongitude();
                        Float speed = location.getSpeed();
                        Long timeStamp = location.getTime();
                        Float accuracy = location.getAccuracy();

                        this.lat = lat.toString();
                        this.lon = lon.toString();
                        this.time = timeStamp.toString();
                        this.locationProvider = location.getProvider();                                                                     
                    }
                    else{
                        Log.d(TAG, "Location fetched is null"); 
                    }
             }
             catch (SecurityException e) {
             Log.d(TAG, "This is a Security Exception");            
                e.printStackTrace();
            }
            catch(IllegalArgumentException e){
            Log.d(TAG, "This is an Illegal Argument Exception");            
                e.printStackTrace();
            }                        

        } catch (Exception e) {
            Log.d(TAG, "Location could not be fetched");
            e.printStackTrace();                        
        }
    }

    private void requestLocationUpdate(){

        LocationManager lm2 = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);                      
            try{            
                // Identify a listener that responds to location updates LocationListener       
                LocationListener locationListener = new LocationListener() {
                    Handler MAIN_HANDLER = new Handler(Looper.getMainLooper()); 
                    public void onLocationChanged(Location location) 
                    { 
                        final Location result = location;                       
                        // Called when a new location is found by the network location provider.                     
                         MAIN_HANDLER.post( new Runnable() { 
                            @Override
                            public void run() {                            
                               Log.d(TAG, "Latitude : " + Double.toString(result.getLatitude()));
                               Log.d(TAG, "Longitude : " + Double.toString(result.getLongitude()));
                               Log.d(TAG, "Time : " + Long.toString(result.getTime()));
                               Log.d(TAG, "Accuracy : " + Float.toString(result.getAccuracy()));
                            }
                         });
                    } 
                    public void onStatusChanged(String provider, int status, Bundle extras) {}
                    public void onProviderEnabled(String provider) {}
                    public void onProviderDisabled(String provider) {} 
                };

                // Register the listener with the Location Manager to receive location updates
                HandlerThread t = new HandlerThread("my handler thread");
                t.start();
                try{
                    if(lm2.isProviderEnabled(LocationManager.GPS_PROVIDER))
                     {
                        Log.d(TAG, "Location Fetching from GPS");                       
                        lm2.requestSingleUpdate(LocationManager.GPS_PROVIDER,locationListener,t.getLooper());
                        lm2.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30 * 1000, 0, locationListener,t.getLooper());                                                                                             
                     }
                     else
                     {
                        Log.d(TAG, "Location Fetching from Network");
                        lm2.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30 * 1000, 0, locationListener,t.getLooper());
                     }
                 }
                 catch (SecurityException e) {
                    lm2.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60 * 1000, 0, locationListener,t.getLooper());
                     Log.d(TAG, "This is a Security Exception");            
                        e.printStackTrace();
                    }
                 catch(IllegalArgumentException e){
                    lm2.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,  60 * 1000, 0, locationListener,t.getLooper());
                    Log.d(TAG, "This is an Illegal Argument Exception");            
                        e.printStackTrace();
                    }                       
            }
            catch(Exception e){
                Log.d(TAG,"An error occured in forced location fetching");
                e.printStackTrace();
            }                       
    }
    private void wakeLockEnable(){
        if (wl == null) {
            Log.d(TAG, "Creating and acquiring wake lock...");
            PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
            this.wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "doWork()");
            wl.setReferenceCounted(false);
            if (!wl.isHeld()) {
                wl.acquire();
                Log.i(TAG, "Acquired wake lock!");
            }
        } else {
            if (!wl.isHeld()) {
                Log.d(TAG, "Wake lock not held...Acquiring wake lock...");
                wl.acquire();
            }
        }
    }

    private void releaseWakeLock(){
        if (wl != null) {
            Log.i(TAG, "wl is not null");
            if (wl.isHeld()) {                
                    Log.i("WakeLock", "We have a wake lock....Releasing wake lock...");
                wl.release();
            }
        }
    }

0 个答案:

没有答案