3

我已尝试连接到 Nearby Messages API,并已成功订阅。

现在,由于某种原因,我的 mMessageListener 字段永远不会收到回调。我已经使用 Android 信标服务演示应用程序使用邻近信标 api 配置了我的信标。

public class MainActivity extends AppCompatActivity implements
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

// Declaration of member variables
private GoogleApiClient mGoogleApiClient;
private final String TAG = "Bridge.MainActivity";
private boolean mResolvingError = false;
private static final int REQUEST_RESOLVE_ERROR = 100;
private static final int REQUEST_PERMISSION = 42;


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

    // Initializing the Google API client


}


private MessageListener mMessageListener = new MessageListener() {
    @Override
    public void onFound(Message message) {
        // Do something with the message
        Log.i(TAG, " Found Message : " + message.toString());
    }

    @Override
    public void onLost(Message message) {
        super.onLost(message);
        Log.i(TAG, " Found Message : " + message.toString());
    }
};

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.d(TAG, "GoogleAPi Client Connected");
    foregorundSubscribeBeacons();
}

@Override
public void onConnectionSuspended(int i) {
    Log.d(TAG, "Google Api Connection Suspended : " + i);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.d(TAG, "GoogleApi Connection failed : " + connectionResult.getErrorMessage());
}

public void foregorundSubscribeBeacons() {
    // Subscribe to receive messages
    Log.i(TAG, "Trying to subscribe");
    if (!mGoogleApiClient.isConnected()) {
        if (!mGoogleApiClient.isConnecting()) {
            mGoogleApiClient.connect();
        }
    } else {
        SubscribeOptions options = new SubscribeOptions.Builder()
                .setStrategy(Strategy.BLE_ONLY)
                .setCallback(new SubscribeCallback() {
                    @Override
                    public void onExpired() {
                        Log.i(TAG, "No longer subscribing.");
                    }
                }).build();

        Nearby.Messages.subscribe(mGoogleApiClient, mMessageListener, options)
                .setResultCallback(new ResultCallback<Status>() {
                    @Override
                    public void onResult(Status status) {
                        if (status.isSuccess()) {
                            Log.i(TAG, "Subscribed successfully.");

                        } else {
                            Log.i(TAG, "Could not subscribe.");
                            // Check whether consent was given;
                            // if not, prompt the user for consent.
                            handleUnsuccessfulNearbyResult(status);
                        }
                    }
                });

    }
}

private void handleUnsuccessfulNearbyResult(Status status) {
    Log.i(TAG, "Processing error, status = " + status);
    if (mResolvingError) {
        // Already attempting to resolve an error.
        return;
    } else if (status.hasResolution()) {
        try {
            mResolvingError = true;
            status.startResolutionForResult(this,
                    REQUEST_RESOLVE_ERROR);
        } catch (IntentSender.SendIntentException e) {
            mResolvingError = false;
            Log.i(TAG, "Failed to resolve error status.", e);
        }
    } else {
        if (status.getStatusCode() == CommonStatusCodes.NETWORK_ERROR) {
            Toast.makeText(this.getApplicationContext(),
                    "No connectivity, cannot proceed. Fix in 'Settings' and try again.",
                    Toast.LENGTH_LONG).show();
        } else {
            // To keep things simple, pop a toast for all other error messages.
            Toast.makeText(this.getApplicationContext(), "Unsuccessful: " +
                    status.getStatusMessage(), Toast.LENGTH_LONG).show();
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_RESOLVE_ERROR) {
        // User was presented with the Nearby opt-in dialog and pressed "Allow".
        mResolvingError = false;
        if (resultCode == RESULT_OK) {
            // Execute the pending subscription and publication tasks here.
           foregorundSubscribeBeacons();
        } else if (resultCode == RESULT_CANCELED) {
            // User declined to opt-in. Reset application state here.
        } else {
            Toast.makeText(this, "Failed to resolve error with code " + resultCode,
                    Toast.LENGTH_LONG).show();
        }
    }
}

@Override
protected void onStart() {
    super.onStart();
    //Initiate connection to Play Services
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Nearby.MESSAGES_API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
    mGoogleApiClient.connect();

    //The location permission is required on API 23+ to obtain BLE scan results
    int result = ActivityCompat
            .checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
    if (result != PackageManager.PERMISSION_GRANTED) {
        //Ask for the location permission
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                REQUEST_PERMISSION);
    }
}

@Override
protected void onStop() {
    super.onStop();
    //Tear down Play Services connection
    if (mGoogleApiClient.isConnected()) {
        Log.d(TAG, "Un-subscribing…");

        mGoogleApiClient.disconnect();
    }
}
4

2 回答 2

3

确保 Beacon Service Demo App 和使用 Nearby Messages 的应用程序是同一个 Google Developers Console 项目的一部分。您只会看到您自己的项目附加的消息。

于 2016-02-08T17:57:36.953 回答
1

如果您已成功完成信标注册,则将附件添加到 Google Beacon 注册服务器上的信标;然后在设备上成功订阅。

预先准备是必要的,否则您将无法获得设备上的东西。

因此,当检测到信标时,onFound(Message msg)会为各个信标的每个附件调用。他们清楚地说,在 onFound() 中“对消息做一些事情”,所以只在那里处理你的附件,而不是在 onFound() 的外部。

在这里,如果您将变量 msg 打印到 Log 中,它应该如下所示:

Message{namespace='yourprojectname-1234', type='abcd', content=[614 bytes], devices=[NearbyDevice{id=NearbyDeviceId{UNKNOWN}}]}

msg.getContent()使用String 变量获取附件内容。这是普通文本,而不是 base64 格式。一旦你得到字符串内容,做任何你想做的事。

现在由您决定附件中的内容。

我在附件中使用了 JSON 并成功处理了我的目的。

于 2016-02-23T10:47:58.367 回答