Android: приемник геозон не звонит

Я только что сделал демонстрацию для Geo Fencing в Android в соответствии с документацией, но здесь Geo Fencing Broadcast Receiver не звонит, когда я выхожу из зоны забора или вхожу в нее.

Ребята посмотрите код и попытайтесь поймать проблему.

Спасибо, Кинго.

SplashActivity.java

public class SplashActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        List<Geofence> mCurrentGeofences = new ArrayList<Geofence>();

        SimpleGeofence mUIGeofence1 = new SimpleGeofence("1",
        // Get latitude, longitude, and radius from the UI
                26.87473379143512, 75.78373555021025, 1,
                // Set the expiration time
                Geofence.NEVER_EXPIRE,
                // Only detect entry transitions
                Geofence.GEOFENCE_TRANSITION_ENTER);

        /*
         * Add Geofence objects to a List. toGeofence() creates a Location
         * Services Geofence object from a flat object
         */
        mCurrentGeofences.add(mUIGeofence1.toGeofence());

        // Start the request. Fail if there's already a request in progress
        try {
            // Try to add geofences
            GeofenceRequester mGeofenceRequester = new GeofenceRequester(this);
            mGeofenceRequester.addGeofences(mCurrentGeofences);
        } catch (UnsupportedOperationException e) {
        }

    }
}

GeoFenceRequestor.java

private PendingIntent createRequestPendingIntent() {

    // If the PendingIntent already exists
    if (null != mGeofencePendingIntent) {

        // Return the existing intent
        return mGeofencePendingIntent;

        // If no PendingIntent exists
    } else {

        // Create an Intent pointing to the IntentService
        Intent intent = new Intent(
                "com.example.demo.ACTION_RECEIVE_GEOFENCE");

        // MAKE SURE YOU CHANGE THIS TO getBroadcast if you are coming from
        // the sample code.
        return PendingIntent.getBroadcast(mActivity, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
}


@Override
public void onAddGeofencesResult(int statusCode, String[] geofenceRequestIds) {

    // Create a broadcast Intent that notifies other components of success
    // or failure
    Intent broadcastIntent = new Intent();

    // Temp storage for messages
    String msg;

    // If adding the geocodes was successful
    if (LocationStatusCodes.SUCCESS == statusCode) {

        // Create a message containing all the geofence IDs added.
        msg = mActivity.getString(R.string.add_geofences_result_success,
                Arrays.toString(geofenceRequestIds));

        // In debug mode, log the result
        Log.d(GeofenceUtils.APPTAG, msg);

        // Create an Intent to broadcast to the app
        broadcastIntent.setAction(GeofenceUtils.ACTION_GEOFENCES_ADDED)
                .addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES)
                .putExtra(GeofenceUtils.EXTRA_GEOFENCE_STATUS, msg);
        // If adding the geofences failed
    } else {

        /*
         * Create a message containing the error code and the list of
         * geofence IDs you tried to add
         */
        msg = mActivity.getString(R.string.add_geofences_result_failure,
                statusCode, Arrays.toString(geofenceRequestIds));

        // Log an error
        Log.e(GeofenceUtils.APPTAG, msg);

        // Create an Intent to broadcast to the app
        broadcastIntent.setAction(GeofenceUtils.ACTION_GEOFENCE_ERROR)
                .addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES)
                .putExtra(GeofenceUtils.EXTRA_GEOFENCE_STATUS, msg);
    }

    // Broadcast whichever result occurred
    LocalBroadcastManager.getInstance(mActivity).sendBroadcast(
            broadcastIntent);

    // Disconnect the location client
    requestDisconnection();
}

GeofenceReceiver.java

открытый класс GeofenceReceiver расширяет BroadcastReceiver { Context context;

    Intent broadcastIntent = new Intent();

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;

        broadcastIntent.addCategory(GeofenceUtils.CATEGORY_LOCATION_SERVICES);
        Toast.makeText(context, "Receiver", Toast.LENGTH_LONG).show();
        if (LocationClient.hasError(intent)) {
            handleError(intent);
        } else {
            handleEnterExit(intent);
        }
    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.demo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />

        <activity
            android:name=".SplashActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".GeofenceReceiver"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.example.demo.ACTION_RECEIVE_GEOFENCE" />
            </intent-filter>
        </receiver>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>

</manifest>

Он успешно добавляет Geo Fence, но позже он не вызывает широковещательный приемник, чтобы узнать, вошел ли / вышел ли


person android    schedule 19.02.2014    source источник
comment
в вашем SplashActivity вы не обрабатываете исключение (как правило, плохая идея). Ваша переменная mGeofenceRequester почти сразу выходит из области видимости... вы уверены, что хотите, чтобы это произошло?   -  person David M    schedule 19.02.2014
comment
В моем приведенном выше коде нет исключений, просто получатель не звонит, но он должен   -  person android    schedule 19.02.2014
comment
Вам удалось решить эту проблему?   -  person MrDumb    schedule 28.08.2014


Ответы (1)


Android GeoFences никогда не включают GPS (потому что их API ужасен, а энергопотребление устройства уже выходит из-под контроля). Вы должны настроить свои геозоны, а затем постоянно опрашивать GPS отдельно, если вы хотите использовать геозоны через GPS.

person stealthwang    schedule 11.03.2014
comment
Действительно? Опрос GPS? У вас есть ссылка на это? - person zundi; 09.07.2018
comment
Что касается моего комментария в 2014 году, это было реальностью для версии Android, на которой я работал (KitKat iirc). Я тоже не мог в это поверить. Официальная документация по API определения местоположения практически отсутствовала в отношении того, как было принято решение использовать GPS. Вы можете просто включить GPS среди входных данных, используемых API определения местоположения, и ничего больше. Экспериментальным путем я обнаружил, что ручная активация оборудования GPS принудительно вводила новые GPS-координаты в этот API, благодаря чему мои геозоны работали с точностью, на которую я надеялся. Возможно, подсистема определения местоположения была улучшена. Я не занимался Android-разработкой уже много лет. - person stealthwang; 10.07.2018