附近的消息API不会触发MessageLisenter

时间:2017-12-14 18:22:37

标签: android iot android-things google-nearby

我正在与恩智浦i.MX7D合作开展物联网项目。在这个项目中,我使用Google Nearby API将伴侣应用程序中的数据发布到了应用程序应用程序。我已经关注了这个项目nearby-kotlin。我几乎完全遵循这个回购。但在我的情况下,我的应用程序都是发布订阅成功。以下是我的两个活动的代码,第一个是配套应用程序的Implicits.File.format,第二个是用于在恩智浦i.MX7D上运行的活动

MainActiviy.kt

在应用程序上运行的应用程序的活动

class MainActivity : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {


/**
 * The entry point to Google Play Services.
 */
private var mGoogleApiClient: GoogleApiClient? = null

/**
 * A [MessageListener] for processing messages from nearby devices.
 */
private var messageListener: MessageListener? = null



/**
 * One minutes.
 */
private val ttlInSeconds = 60 * 3
/**
 * Sets the time in seconds for a published message or a subscription to live. Set to three
 * minutes in this sample.
 */
private val publishSubscriptionStrategy = Strategy.Builder().setTtlSeconds(ttlInSeconds).build()


private val savedInstance = Calculate::class.java.simpleName

private val TAG = MainActivity::class.java.simpleName

private val keyUUID: String = "UUID_KEY"

private lateinit var calculation: Calculate

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    calculation = savedInstanceState?.get(savedInstance) as Calculate? ?:
            Calculate.builder(getUUID(getSharedPreferences(applicationContext.packageName, Context.MODE_PRIVATE)),
                    "0", "0", Operator.OPERATOR_PLUS)

    val binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
    binding.calculate = calculation

    setOperatorDrawable(calculation.operator)


    messageListener = object : MessageListener() {
        override fun onFound(message: Message) {
            Calculate.fromMessage(message).toString()
            resultTv.text = calculation.result
        }

        override fun onLost(message: Message) {

        }
    }

    if (mGoogleApiClient != null && mGoogleApiClient!!.isConnected)
        subscriberForMessage()


    fab_plus.setOnClickListener {
        publishMessage()
        calculation.operator = "Plus"
        calculation.operandOne = operandOneET.text.toString()
        calculation.operandTwo = operandTwoET.text.toString()
        setOperatorDrawable(calculation.operator)
    }

    fab_minus.setOnClickListener {
        Log.i(TAG, "minus clicked")
        publishMessage()
        calculation.operator = "Minus"
        calculation.operandOne = operandOneET.text.toString()
        calculation.operandTwo = operandTwoET.text.toString()
        setOperatorDrawable(calculation.operator)
    }

    fab_multiply.setOnClickListener {
        publishMessage()
        calculation.operator = "Multiply"
        calculation.operandOne = operandOneET.text.toString()
        calculation.operandTwo = operandTwoET.text.toString()
        setOperatorDrawable(calculation.operator)
    }

    fab_divide.setOnClickListener {

        if (calculation.operandTwo.equals("0")) {
            Snackbar.make(resultTv, "Divide by zero exception", Snackbar.LENGTH_SHORT).show()

            return@setOnClickListener
        }
        publishMessage()
        calculation.operator = "Divide"
        calculation.operandOne = operandOneET.text.toString()
        calculation.operandTwo = operandTwoET.text.toString()
        setOperatorDrawable(calculation.operator)
    }

    buildGoogleApiClient()
}


private fun setOperatorDrawable(operator: String?) {

    when (operator) {
        "Plus" -> operatorIV.setImageResource(android.R.drawable.ic_input_add)
        "Minus" -> operatorIV.setImageResource(R.drawable.ic_minus_symbol)
        "Multiply" -> operatorIV.setImageResource(R.drawable.ic_multiply)
        else -> operatorIV.setImageResource(R.drawable.ic_divide)
    }
}


private fun getUUID(sharedPreferences: SharedPreferences): String {
    var uuid = sharedPreferences.getString(keyUUID, "")

    if (uuid.isEmpty()) {
        uuid.apply {
            uuid = UUID.randomUUID().toString()
            sharedPreferences.edit().putString(keyUUID, this).apply()
        }
    }

    return uuid
}

override fun onSaveInstanceState(outState: Bundle?) {
    super.onSaveInstanceState(outState)

    outState?.putSerializable(savedInstance, calculation)
}

private fun buildGoogleApiClient() {

    if (mGoogleApiClient != null)
        return


    mGoogleApiClient = GoogleApiClient.Builder(this@MainActivity)
            .addApi(Nearby.MESSAGES_API)
            .addConnectionCallbacks(this@MainActivity)
            .enableAutoManage(this@MainActivity, this@MainActivity)
            .build()
}


/**
 * Publishes a message to nearby devices and updates the UI if the publication either fails or
 * TTLs.
 */
private fun publishMessage() {
    Log.i(TAG, "publishing msg")


    val option: PublishOptions = PublishOptions.Builder().setStrategy(publishSubscriptionStrategy)
            .setCallback(object : PublishCallback() {
                override fun onExpired() {
                    super.onExpired()

                    Log.i(TAG, "Message Publish expired")
                    runOnUiThread { Snackbar.make(resultTv, "Publish expired", Snackbar.LENGTH_SHORT).show() }
                }
            }).build()

    Nearby.Messages.publish(mGoogleApiClient, calculation.toMessage(), option)
            .setResultCallback { status ->
                if (status.isSuccess) {
                    Log.i(TAG, "publishing was successful")
                    Snackbar.make(resultTv, "publishing successful", Snackbar.LENGTH_SHORT).show()
                } else {
                    Snackbar.make(resultTv, "Couldn't publish " + status, Snackbar.LENGTH_SHORT).show()
                }

            }

}

/**
 * Subscribes to messages from nearby devices and updates the UI if the subscription either
 * fails or TTLs.
 */
private fun subscriberForMessage() {
    Log.i(TAG, "Subscribing")

    val option: SubscribeOptions = SubscribeOptions.Builder().setStrategy(publishSubscriptionStrategy)
            .setCallback(object : SubscribeCallback() {
                override fun onExpired() {
                    super.onExpired()

                    Log.i(TAG, "Subscription expired")
                    runOnUiThread { Snackbar.make(resultTv, "Subscription expired", Snackbar.LENGTH_SHORT).show() }
                }
            }).build()

    Nearby.Messages.subscribe(mGoogleApiClient, messageListener, option)
            .setResultCallback { status ->
                if (status.isSuccess) {
                    Log.i(TAG, "subscription was successful")
                    Snackbar.make(resultTv, "Subscription successful", Snackbar.LENGTH_SHORT).show()
                } else {
                    Snackbar.make(resultTv, "Couldn't subscribe " + status, Snackbar.LENGTH_SHORT).show()
                }

            }

}

/**
 * Stops publishing message to nearby devices.
 */
private fun unpublish() {
    Log.i(TAG, "Unpublishing.")
    Nearby.Messages.unpublish(mGoogleApiClient, calculation.toMessage())
}


override fun onConnected(bundle: Bundle?) {
    Log.i(TAG, "GoogleApiClient connected")
    Snackbar.make(resultTv, "GoogleApiClient connected", Snackbar.LENGTH_SHORT).show()

    publishMessage()
    subscriberForMessage()
}

override fun onConnectionSuspended(i: Int) {
    Snackbar.make(resultTv, "Google Api connection Suspended", Snackbar.LENGTH_SHORT).show()
 }

override fun onConnectionFailed(connectionResult: ConnectionResult) {
    Snackbar.make(resultTv, "connection Failed" + connectionResult.errorMessage, Snackbar.LENGTH_SHORT).show()
 } }

如果你们需要检查已经使用Gson序列化和反序列化的类来作为有效载荷发送到mymy消息,那么这个calsses是Calculate&amp; Calculation

这是物联网的Hello世界类型项目。感谢帮助和建议。

谢谢是提前

1 个答案:

答案 0 :(得分:0)

事实证明,使用Google附近的API非常棘手。在我的 JAVA 代码中,我遇到了同样的问题,直到 today 为止,它一直运行良好。我创建了 NearbyManager 类,以帮助自动化和清除主线代码。突然我无法发布。 我的发布成功回调从未触发我也没有收到任何消息

查看您的日志,我发现我的 API密钥不被Google接受(我清除了日志,所以没有任何问题!),因为我的 SHA1(Android调试密钥)指纹已更改(同样,对于我来说,为什么没有人解释,我将不胜感激),所以我去了我的 Console 更新了我的指纹。这可能已经奏效,尽管距离我进行更改已经很长时间了,但是我还没有看到结果或测试。

我的代码不是解决问题的方法,而是更多的先决条件,可以使人们开始使用 Nearby API !我们没有这样的支持班,所以我认为这可以帮助任何起步的人这应该可以帮助您找到难题中缺少的部分!祝你好运!

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.widget.Toast;
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.MessagesClient;
import com.google.android.gms.nearby.messages.PublishCallback;
import com.google.android.gms.nearby.messages.PublishOptions;
import com.google.android.gms.nearby.messages.Strategy;
import com.google.android.gms.nearby.messages.SubscribeCallback;
import com.google.android.gms.nearby.messages.SubscribeOptions;
import com.google.android.gms.tasks.OnSuccessListener;

public class NearbyManager {
    private boolean isSubscribing = false;
    private boolean isPublishing = false;
    private Activity current;
    private MessagesClient mMessageClient;
    private MessageListener mMessageListener;
    private static final Strategy PUB_STRATEGY = new Strategy.Builder()
            .setTtlSeconds(Strategy.TTL_SECONDS_DEFAULT).build();
    private static final Strategy SUB_STRATEGY = new Strategy.Builder()
            .setTtlSeconds(Strategy.TTL_SECONDS_MAX).build();
    private String mPubMessage;


    public boolean isSubscribing() {
        return isSubscribing;
    }

    public boolean isPublishing() {
        return isPublishing;
    }

    public NearbyManager(Activity activity){
        current = activity;
        PermissionManager.checkPerms(current);
        mMessageClient = Nearby.getMessagesClient(current);
        mMessageListener = new MessageListener(){
            @Override
            public void onFound(Message message) {
                if(message != null){
                    //DO SOMETHING
                    }
                }
            }
            @Override
            public void onLost(Message message) {
                Toast.makeText(current, "Device is lost", Toast.LENGTH_SHORT).show();
            }
        };

    }
    public void publish(final String message){
        mPubMessage = message;
        PublishOptions options = new PublishOptions
                .Builder()
                .setStrategy(PUB_STRATEGY)
                .setCallback(new PublishCallback(){
                    @Override
                    public void onExpired() {
                        super.onExpired();
                        current.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                isPublishing = false;
                            }
                        });
                    }
                })
                //.setStrategy(Strategy.BLE_ONLY) <-- removed this
                .build();
        mMessageClient.publish(new Message(message.getBytes()), options).addOnSuccessListener(current, new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Toast.makeText(current, "Publishing! Message:" + message, Toast.LENGTH_SHORT).show();
            }
        });
        isPublishing = true;
    }
    public void subscribe(){
        SubscribeOptions options = new SubscribeOptions.Builder()
                .setStrategy(SUB_STRATEGY)
                .setCallback(new SubscribeCallback(){
                    @Override
                    public void onExpired() {
                        super.onExpired();
                        Toast.makeText(current, "No longer Subscribing!", Toast.LENGTH_SHORT).show();
                        current.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                isSubscribing = false;
                            }
                        });
                    }
                })
                //.setStrategy(Strategy.BLE_ONLY) <-- removed this
                .build();
        mMessageClient.subscribe(mMessageListener, options).addOnSuccessListener(current, new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Toast.makeText(current, "Subscribing!", Toast.LENGTH_SHORT).show();
            }
        });
        isSubscribing = true;
    }
    public void unsubscribe(){
        if(isSubscribing && mMessageClient != null)
            mMessageClient.unsubscribe(mMessageListener);
        isSubscribing = false;
    }
    public void unpublish(){
        if(isPublishing && mMessageClient != null)
            mMessageClient.unpublish(new Message(mPubMessage.getBytes()));
        isPublishing = false;
    }

}

我要提出的一项建议是通过在函数调用主体中放置Log或Toast语句来跟踪函数调用。像在mMessageListener内部一样,进行发布和订阅。

另外,我没有阅读太多代码,但希望您使用onSuccessListeners以编程方式检查发布和订阅是否成功。