Autore Topic: Beacon non rilevato in un Service  (Letto 340 volte)

Offline Fededark

  • Nuovo arrivato
  • *
  • Post: 1
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Samsung Galaxy Note 3
  • Sistema operativo:
    Windows 10
Beacon non rilevato in un Service
« il: 22 Luglio 2016, 14:44:27 CEST »
0
Salve a tutti!

Sto creando un app che utilizza dei Beacon per identificare la posizione di un utente e per farlo sto utilizzando le GoogleAPI.
Ho registrato il Beacon e vorrei creare un Service che permetta scansioni programmate ogni tot minuti anche quando l'app non è attiva.

Il problema è che se provo a creare il GoogleApiClient all'interno del servizio questo sembra non rilevare il Beacon, mentre facendo la stessa identica cosa all'interno di un'Activity non si presenta nessun problema.
Come mai accade ciò?

Vi allego il codice del Service

Codice (Java): [Seleziona]
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.nfc.Tag;
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;

/**
 * Created by Federico on 18/07/2016.
 */

public class BeaconMessageReceiver extends Service {

    private static final String TAG = "BeaconMessageReceiver";

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

    @Override
    public void onCreate() {
        super.onCreate();

        sharedPreferences =
                getSharedPreferences(getString(R.string.shared_preference), Context.MODE_PRIVATE);

        SharedPreferences.Editor editor = sharedPreferences.edit()
                .putString(getString(R.string.service), getString(R.string.service_running));
        editor.apply();

        createGoogleApiClient();
        createMessageListener();
        mGoogleApiClient.connect();
        Log.d(TAG, "BeaconMessageReceiver created");
    }



    @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) {
        Log.d(TAG, "onStartCommand");
        return START_STICKY;
    }

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

    public void checkBeacon() {
        Log.d(TAG, "checkBeacon");
        toggleBluetooth();
        subscribe();
    }

    private void createGoogleApiClient() {
        Log.d(TAG, "createGoogleApiClient");
        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(new GoogleApiClient.ConnectionCallbacks() {
                        @Override
                        public void onConnected(@Nullable Bundle bundle) {
                            Log.d(TAG, "Connected");
                            checkBeacon();
                        }

                        @Override
                        public void onConnectionSuspended(int i) {

                        }
                    })
                    .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                        @Override
                        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                        }
                    })
                    .build();
        }
    }

    private void createMessageListener() {

        Log.d(TAG, "createMessageListener");

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

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

    // 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();
    }
}

e il Log della console

Codice: [Seleziona]
07-22 14:30:08.323 16108-16108/com.federicoxella.biblio D/BeaconMessageReceiver: createGoogleApiClient
07-22 14:30:08.443 16108-16108/com.federicoxella.biblio D/BeaconMessageReceiver: createMessageListener
07-22 14:30:08.513 16108-16108/com.federicoxella.biblio D/BeaconMessageReceiver: BeaconMessageReceiver created
07-22 14:30:08.513 16108-16108/com.federicoxella.biblio D/BeaconMessageReceiver: onStartCommand
07-22 14:30:09.033 16108-16108/com.federicoxella.biblio D/BeaconMessageReceiver: Connected
07-22 14:30:09.033 16108-16108/com.federicoxella.biblio D/BeaconMessageReceiver: checkBeacon
07-22 14:30:09.073 16108-16108/com.federicoxella.biblio I/BeaconMessageReceiver: Subscribing for updates.

Sembra quasi che la onFound del MessageListener non venga chiamata..

minSdkVersion 19, targetSdkVersion 23