Android在应用启动时无法运行服务

时间:2017-08-30 17:44:07

标签: android service location

只要我的Android应用启动,它也会启动一个LocationService,每隔几秒就会发送一次手机的当前位置。

我在Android 5.1.1上的三星Galaxy J3(2016)上测试了这个应用程序,一旦应用程序启动,弹出窗口显示" AwesomeApp已停止"。点击" OK"我仍然可以使用该应用程序,但每次位置服务启动时出现错误对话框。我知道它是LocationService,因为当我禁用启动时,一切正常,没有错误对话框。

这是日志显示的内容:

08-30 19:33:37.337 18134-18134/? E/Zygote: MountEmulatedStorage()
08-30 19:33:37.337 18134-18134/? E/Zygote: v2
08-30 19:33:37.337 18134-18134/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
08-30 19:33:37.337 18134-18134/? E/art: setrlimit(RLIMIT_CORE) failed for pid 18134: Operation not permitted
08-30 19:33:37.367 18134-18141/? E/art: Failed writing handshake bytes (-1 of 14): Broken pipe

这就是我的LocationService:

package com.orgname.appname.services;

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;

import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LocationService extends Service {
    private static final String TAG = "LocationService";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 2000;
    private static final float LOCATION_DISTANCE = 0;
    private DatabaseReference mDatabase;
    private String mKey;
    private final OkHttpClient mClient = new OkHttpClient();
    private Gson mGson;

    private class LocationListener implements android.location.LocationListener {
        Location mLastLocation;

        public LocationListener(Location lastLocation) {
            Log.e(TAG, "LocationListener " + lastLocation);
            mLastLocation = lastLocation;
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location);
            mLastLocation.set(location);

//            writeNewLocation(mKey, location);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {
            Log.e(TAG, "onStatusChanged: " + s);
        }

        @Override
        public void onProviderEnabled(String s) {
            Log.e(TAG, "onProviderEnabled: " + s);
        }

        @Override
        public void onProviderDisabled(String s) {
            Log.e(TAG, "onProviderDisabled: " + s);
        }
    }

    LocationListener[] mLocationListeners = new LocationListener[]{
            new LocationListener(new Location(LocationManager.GPS_PROVIDER)),
            new LocationListener(new Location(LocationManager.NETWORK_PROVIDER))
    };

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        Log.e(TAG, "onCreate");
        FirebaseApp.initializeApp(getApplicationContext());
        mDatabase = FirebaseDatabase.getInstance().getReference();
        mKey = mDatabase.child("locationsArray").push().getKey();
        mGson = new Gson();
        initializeLocationManager();

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

    private void writeNewLocation(String userId, Location location) {
        HashMap<String, Double> newLocation = new HashMap<>();
        newLocation.put("lat", location.getLatitude());
        newLocation.put("lng", location.getLongitude());

        Request request = new Request.Builder()
                .url("https://{REDACTED}")
                .patch(RequestBody.create(JSON, mGson.toJson(newLocation)))
                .build();

        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                Headers responseHeaders = response.headers();
                for (int i = 0, size = responseHeaders.size(); i < size; i++) {
                    System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
                }

                System.out.println(response.body().string());
            }
        });
    }
}

如何防止这种情况发生?

0 个答案:

没有答案