在后台服务中未发现iBeacon

时间:2016-07-21 13:52:58

标签: android service google-nearby

所以这是我的情况:

我正在构建一个需要检查附近是否有注册信标的应用程序(我使用GoogleAPI)。

即使应用程序没有运行,也必须这样做,所以我使用的服务一直运行,直到周围没有信标。

问题在于,如果我在服务中创建GoogleApiClientNearby.Messages.subscribe似乎不起作用,而在Activity中执行相同的操作不会导致任何问题。

这是我服务的代码

import android.Manifest;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.nearby.Nearby;
import com.google.android.gms.nearby.messages.Message;
import com.google.android.gms.nearby.messages.MessageListener;
import com.google.android.gms.nearby.messages.MessagesOptions;
import com.google.android.gms.nearby.messages.NearbyPermissions;
import com.google.android.gms.nearby.messages.Strategy;
import com.google.android.gms.nearby.messages.SubscribeOptions;

public class BeaconMessageReceiver extends Service implements 
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "BeaconMessageReceiver";

    private GoogleApiClient mGoogleApiClient;
    private MessageListener mMessageListener;
    private IBinder mBinder = new LocalBinder();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "BeaconMessageReceiver created");

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(Nearby.MESSAGES_API, new MessagesOptions.Builder()
                            .setPermissions(NearbyPermissions.BLE)
                            .build())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(BeaconMessageReceiver.this)
                    .build();
        }

        createMessageListener();
        mGoogleApiClient.connect();
    }

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

    public class LocalBinder extends Binder {
        public BeaconMessageReceiver getBeaconMessageReceiverInstance() {
            return BeaconMessageReceiver.this;
        }
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        mGoogleApiClient.disconnect();
        Log.d(TAG, "BeaconMessageReceiver destroyed");
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        checkBeacon();
    }

    @Override
    public void onConnectionSuspended(int i) {}

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

    public void checkBeacon() {
        enableBluetooth();        // subscribe in background don't automatically enable BT
        subscribe();
    }

    private void createMessageListener() {

        mMessageListener = new MessageListener() {
            @Override
            public void onFound(Message message) {
                String messageAsString = new String(message.getContent());
                Log.d(TAG, "Found message: " + messageAsString);
                unsubscribe();
                disableBluetooth();
            }

            @Override
            public void onLost(Message message) {
                String messageAsString = new String(message.getContent());
                Log.d(TAG, "Lost sight of message: " + messageAsString);
                unsubscribe();
                disableBluetooth();
            }
        };
    }

    // Subscribe to messages.
    private void subscribe() {

        Log.i(TAG, "Subscribing for updates.");
        SubscribeOptions options = new SubscribeOptions.Builder()
                .setStrategy(Strategy.BLE_ONLY)
                .build();
        Nearby.Messages.subscribe(mGoogleApiClient, mMessageListener, options);
    }

    // Unsubscribe to messages
    private void unsubscribe() {
        Log.i(TAG, "Unsubscribing.");
        Nearby.Messages.unsubscribe(mGoogleApiClient, mMessageListener);
    }

    private void toggleBluetooth() {
        if (!BluetoothAdapter.getDefaultAdapter().isEnabled())
            BluetoothAdapter.getDefaultAdapter().enable();
        else
            BluetoothAdapter.getDefaultAdapter().disable();
        }
    }

MainActivity在onCreate()中启动服务,在onStart()中绑定自身并在onStop()中取消绑定。

1 个答案:

答案 0 :(得分:0)

订阅有两种方式:前景和背景。听起来你想要背景版本,它需要一个PendingIntent,并会在附近发现一个灯塔时启动你的应用程序。

以下是您的应用在后台时查找信标的指南: https://developers.google.com/nearby/messages/android/get-beacon-messages#subscribe_in_the_background