2017-04-22 1 views
0

저는 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" /> 

을 여기 내 로그캣입니다

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

LogCat을 사용하여 충돌과 관련된 Java 스택 추적을 검사하십시오. https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this – CommonsWare

+0

여기 내 logcat입니다. , 오류가 무엇인지 판단 할 수 없습니다 : – Gurchani

+0

그 중에서 Java 스택 추적은 앱에서 발생하지 않습니다. – CommonsWare

답변

0

1 단계 : makeToast()을 제거하십시오.

2 단계 : onCreate() 서비스가 호출 될 때까지 서비스 필드 (예 : mLocationListeners)를 초기화 할 때까지 기다립니다.

그대로 필드 이니셜 라이저에서 Toast을 표시하려하고 있는데, Service이 아직 설정되지 않았기 때문에 작동하지 않습니다.

+0

감사합니다. 내 문제가 해결되었습니다. Merci – Gurchani