2016-07-28 12 views
0

私はBOOT_COMPLETEDと放送受信機を使用しなければならないことを知っています。しかし、私は放送受信機からGeofenceを登録するためのサンプルが必要です。私はGeofenceサービスを作成し、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は常にnullで接続されていません。 addGeofenceはメソッドです。 –

+0

さて、あなたはあなたの 'サービス'を稼働させる必要があります。あなたの質問は、再起動時に問題を起こしていることを意味します。 'Service'が最初に動作するようにしてから、リブートの問題を解決してください(まだ存在する場合)。 –

+0

私は間違いをどこにしているか教えてください。私は初心者です。私は答えが私を助けることを願っています –

関連する問題