2016-07-28 110 views
0

我知道我必須使用BOOT_COMPLETED和廣播接收器。但我只需要一個樣本來從Broadcast receiver註冊Geofence。我創建了一個Geofence服務calss,並嘗試從BroadcastReceiver啓動它,但它不起作用。如何在手機重新啓動時註冊地理圍欄?

public class BootCompleteReceiver extends BroadcastReceiver { 


@Override 
public void onReceive(Context context, Intent intent) { 
    //Or whatever action your receiver accepts 
    if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){ 
     Toast.makeText(context , "APP REBBOT RECEIVED" , Toast.LENGTH_LONG).show(); 
     Intent serviceIntent = new Intent(context , GeoFenceObserversationService.class); 
     context.startService(serviceIntent); 

     // GeoFenceObserversationService.getInstant().addGeofences(); 

    } 
}} 

這裏是我的服務類

這裏是我的清單文件。

<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.cctspl.geofenceex"> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> 
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> 

<application 
    android:allowBackup="true" 
    android:name=".MyApplication" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 

    android:supportsRtl="true" 
    android:theme="@style/AppTheme"> 
    <activity android:name=".MainActivity"> 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <service 
     android:name=".GeofenceTransitionsIntentService" 
     android:exported="true" /> 
    <service android:name=".GeoFenceObserversationService"/> 
    <receiver android:name=".BootCompleteReceiver" 
     android:exported="true"> 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED"/> 
     </intent-filter> 
    </receiver> 
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"></meta-data> 
    <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyDcbHjgBC7OTfdrwKjlnag9aQU4_-3IVaw" /> 
</application> 

public class GeoFenceObserversationService extends Service implements GoogleApiClient.ConnectionCallbacks , GoogleApiClient.OnConnectionFailedListener , ResultCallback<Status> { 
protected static final String TAG = "GeoFenceObserversationService"; 
protected GoogleApiClient mGoogleApiClient; 
protected ArrayList<Geofence> mGeofenceList; 
private boolean mGeofencesAdded; 
private SharedPreferences mSharedPreferences; 
private static GeoFenceObserversationService mInstant; 
public static GeoFenceObserversationService getInstant(){ 
    return mInstant; 
} 
@Override 
public void onCreate() { 
    super.onCreate(); 
    mInstant = this; 
    mGeofenceList = new ArrayList<Geofence>(); 
    mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFERENCES_NAME , MODE_PRIVATE); 
    mGeofencesAdded = mSharedPreferences.getBoolean(Constants.GEOFENCES_ADDED_KEY , false); 
    populateGeofenceList(); 
    buildGoogleApiClient(); 
    addGeofences(); 
} 
public static final HashMap<String ,LatLng> BAY_AREA_LANDMARKS = new HashMap<String,LatLng>(); 
static 
{ 
    BAY_AREA_LANDMARKS.put("Rajakilpakkam" , new LatLng(12.915450, 80.150437)); 

    BAY_AREA_LANDMARKS.put("HANSE GARDEN" , new LatLng(12.911120, 80.156161)); 

} 

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

protected void buildGoogleApiClient() { 

     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
      } 

@Override 
public void onDestroy() { 
    mGoogleApiClient.disconnect(); 
    super.onDestroy(); 
} 

private GeofencingRequest getGeofencingRequest() { 
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); 
    builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); 
    builder.addGeofences(mGeofenceList); 
    return builder.build(); 
} 
public void populateGeofenceList() { 
    for (Map.Entry<String, LatLng> entry : BAY_AREA_LANDMARKS.entrySet()) { 
     mGeofenceList.add(new Geofence.Builder() 
       // Set the request ID of the geofence. This is a string to identify this 
       // geofence. 
       .setRequestId(entry.getKey()) 
       // Set the circular region of this geofence. 
       .setCircularRegion(
         entry.getValue().latitude, 
         entry.getValue().longitude, 
         100 
       ) 

       // Set the expiration duration of the geofence. This geofence gets automatically 
       // removed after this period of time. 
       .setExpirationDuration(Geofence.NEVER_EXPIRE) 

       // Set the transition types of interest. Alerts are only generated for these 
       // transition. 
       .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT) 

       .build() 
     ); 

    } 
} 

public void addGeofences() { 
    if (!mGoogleApiClient.isConnected()) { 
     Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); 
     return; 
    } 


    if(!mGeofenceList.isEmpty()){ 
     try { 
      LocationServices.GeofencingApi.addGeofences(mGoogleApiClient, getGeofencingRequest(), getGeofencePendingIntent()).setResultCallback(this); 
     } catch (SecurityException securityException) { 
      securityException.printStackTrace(); 
     } 
    } 

} 
public void removeGeofences() { 
    if (!mGoogleApiClient.isConnected()) { 
     Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); 
     return; 
    } 
    try { 
     LocationServices.GeofencingApi.removeGeofences(mGoogleApiClient,getGeofencePendingIntent()).setResultCallback(this); 
    } catch (SecurityException securityException) { 
     securityException.printStackTrace(); 
    } 
} 
private PendingIntent getGeofencePendingIntent() { 
    Intent intent = new Intent(this, GeofenceTransitionsIntentService.class); 
    return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 
} 


@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    return START_STICKY; 
} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 

} 

@Override 
public void onConnectionSuspended(int i) { 

} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

} 

@Override 
public void onResult(@NonNull Status status) { 
    if (status.isSuccess()) { 
     mGeofencesAdded = !mGeofencesAdded; 
     SharedPreferences.Editor editor = mSharedPreferences.edit(); 
     editor.putBoolean(Constants.GEOFENCES_ADDED_KEY, mGeofencesAdded); 
     editor.apply(); 
    } else { 
     String errorMessage = GeofenceErrorMessages.getErrorString(this,status.getStatusCode()); 
     Log.i("Geofence", errorMessage); 
    }}} 

在此先感謝。

我logcat的

07-28 19:14:09.133 20254-20254/com.cctspl.geofenceex E/AndroidRuntime: FATAL EXCEPTION: main 
                    Process: com.cctspl.geofenceex, PID: 20254 
                    java.lang.RuntimeException: Unable to create service com.cctspl.geofenceex.GeoFenceObserversationService: java.lang.IllegalStateException: GoogleApiClient is not connected yet. 
                     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2596) 
                     at android.app.ActivityThread.access$1800(ActivityThread.java:144) 
                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292) 
                     at android.os.Handler.dispatchMessage(Handler.java:102) 
                     at android.os.Looper.loop(Looper.java:136) 
                     at android.app.ActivityThread.main(ActivityThread.java:5154) 
                     at java.lang.reflect.Method.invokeNative(Native Method) 
                     at java.lang.reflect.Method.invoke(Method.java:515) 
                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:780) 
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:596) 
                     at dalvik.system.NativeStart.main(Native Method) 
                    Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet. 
                     at com.google.android.gms.internal.zzod.zzd(Unknown Source) 
                     at com.google.android.gms.internal.zzoh.zzd(Unknown Source) 
                     at com.google.android.gms.internal.zzof.zzd(Unknown Source) 
                     at com.google.android.gms.location.internal.zzf.addGeofences(Unknown Source) 
                     at com.cctspl.geofenceex.GeoFenceObserversationService.addGeofences(GeoFenceObserversationService.java:130) 
                     at com.cctspl.geofenceex.GeoFenceObserversationService.onCreate(GeoFenceObserversationService.java:50) 
                     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2586) 
                     at android.app.ActivityThread.access$1800(ActivityThread.java:144)  
                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1292)  
                     at android.os.Handler.dispatchMessage(Handler.java:102)  
                     at android.os.Looper.loop(Looper.java:136)  
                     at android.app.ActivityThread.main(ActivityThread.java:5154)  
                     at java.lang.reflect.Method.invokeNative(Native Method)  
                     at java.lang.reflect.Method.invoke(Method.java:515)  
                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:780)  
                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:596)  
                     at dalvik.system.NativeStart.main(Native Method)  

回答

0
當你調用 startService()

,該Service不會立即啓動。你只是告訴Android你想要Service開始。 Android會在需要時啓動Service

你只需要撥打startService()即可。我注意到您的ServiceonCreate()已經建立了地理柵欄。你不需要再做一次。

+0

但我沒有在其他地方添加Geofence。我的服務課程也不盡如人意。 mGoogleApiClient始終爲空且未連接。 addGeofence就是一種方法。 –

+0

那麼,你需要讓你的'服務'工作。你的問題意味着你在重啓時遇到問題。你應該讓你的'服務'先工作,然後解決重啓問題(如果它仍然存在)。 –

+0

你能告訴我我在哪裏犯錯。我是一個新手。我希望你的回答會幫助我 –

相關問題