当我调用服务意图时,应用程序会不断崩溃

时间:2017-04-22 18:37:33

标签: android android-intent service

我开始学习android和当前项目中的服务,即使应用程序关闭,我也希望在后台跟踪位置,但是当我从主活动调用服务的意图时整个应用程序崩溃。我已经包含了这项服务:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;


/**
 * Created by Gurchani on 4/21/2017.
 */

public class service  extends Service {
    private static final String TAG = "BOOMBOOMTESTGPS";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 1000;
    private static final float LOCATION_DISTANCE = 10f;
    private localDatabase database;
    SQLiteDatabase db;
    private double UserLong;
    private double UserLat;

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

        public LocationListener(String provider)
        {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
            makeToast();
        }

        @Override
        public void onLocationChanged(Location location)
        {
            Log.e(TAG, "onLocationChanged: " + location);
            mLastLocation.set(location);
            UserLat = mLastLocation.getLatitude();
            UserLong = mLastLocation.getLongitude();
            makeToast();
            doSQLQuery();
        }

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

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

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    private void makeToast() {
        Toast.makeText(this,"its on baby", Toast.LENGTH_LONG).show();
    }

    private int doSQLQuery() {
        double distance = 0.1;

        // Define a projection that specifies which columns from the database
        // you will actually use after this query.
        String[] projection = {
                FeederClass.FeedEntry.barId,
        };

        // Filter results WHERE "title" = 'My Title'
        Cursor c = dis(String.valueOf(Math.cos((double) distance / (double) 6380)), Math.cos(deg2rad(UserLat)), Math.sin(deg2rad(UserLat)), Math.cos(deg2rad(UserLong)), Math.sin(deg2rad(UserLong)));
        Toast.makeText(this,"Your message.", Toast.LENGTH_LONG).show();
        return c.getCount();

    }

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

    @Override
    public IBinder onBind(Intent arg0)
    {
        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");
        initializeLocationManager();
        db = database.getReadableDatabase();

        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 {
                    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);
        }
    }
    public Cursor dis(String dis, double cos_lat_rad, double sin_lat_rad, double cos_lon_rad, double sin_lon_rad) {

        Cursor cursor = db.rawQuery("SELECT barID ,(" + sin_lat_rad + "*\"SinLat\"+" + cos_lat_rad + "*\"CosLat\"*(" + sin_lon_rad + "*\"SinLong\"+" + cos_lon_rad + "*\"CosLong\")) AS \"distance_acos\" FROM BarDetails WHERE ("+sin_lat_rad+" * \"SinLat\" +"+ cos_lat_rad +"* \"CosLat\" * (+"+sin_lon_rad +"* \"SinLong\" + "+cos_lon_rad +"* \"CosLong\")) >"+dis+ " ORDER BY \"distance_acos\" DESC ", null);
        return cursor;

    }

    public static double deg2rad(double deg) {
        return (deg * Math.PI / 180.0);
    }
}

我在我的主要活动中就是这样称呼这项服务:

Intent intent = new Intent(MainActivity.this , service.class);
       startService(intent);

在我的清单文件中,我包括以下内容:

<service android:name=".service" android:process=":my_service" />

这是我的logcat

04-22 21:11:00.960 18698-18698/com.example.android.find:my_service E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                    Process: com.example.android.find:my_service, PID: 18698
                                                                                    java.lang.RuntimeException: Unable to instantiate service com.example.android.findbar.service: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                                        at android.app.ActivityThread.handleCreateService(ActivityThread.java:2962)
                                                                                        at android.app.ActivityThread.access$1800(ActivityThread.java:178)
                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1553)
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                                        at android.os.Looper.loop(Looper.java:194)
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:5631)
                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
                                                                                     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                                        at android.content.ContextWrapper.getResources(ContextWrapper.java:86)
                                                                                        at android.widget.Toast.<init>(Toast.java:106)
                                                                                        at android.widget.Toast.makeText(Toast.java:263)
                                                                                        at com.example.android.findbar.service.makeToast(service.java:71)
                                                                                        at com.example.android.findbar.service.access$000(service.java:19)
                                                                                        at com.example.android.findbar.service$LocationListener.<init>(service.java:37)
                                                                                        at com.example.android.findbar.service.<init>(service.java:90)
                                                                                        at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                                        at java.lang.Class.newInstance(Class.java:1606)
                                                                                        at android.app.ActivityThread.handleCreateService(ActivityThread.java:2959)
                                                                                        at android.app.ActivityThread.access$1800(ActivityThread.java:178) 
                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1553) 
                                                                                        at android.os.Handler.dispatchMessage(Handler.java:111) 
                                                                                        at android.os.Looper.loop(Looper.java:194) 
                                                                                        at android.app.ActivityThread.main(ActivityThread.java:5631) 
                                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                                        at java.lang.reflect.Method.invoke(Method.java:372) 
                                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959) 
                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754) 

1 个答案:

答案 0 :(得分:0)

步骤1:摆脱makeToast()

步骤2:等待初始化服务的字段(例如mLocationListeners),直到服务上调用onCreate()

目前,您尝试在字段初始值设定项中显示Toast,但由于Service尚未设置,因此无效。