从服务中添加TextView?

时间:2014-08-20 12:53:54

标签: java android wear-os

我有一个问题,我似乎无法理解。它的背景是我正在尝试更新Android Wear设备上的视图

我有一个名为 MessageListener 的WearableListenerService,它有一个onMessageReceived函数,如下所示:

public void onMessageReceived(MessageEvent messageEvent) {

    Log.v("WEAR", "MessageListener Triggered");


    MessageObject msg = processMessageEvent(messageEvent);
    // handle only wear messages
    if (msg.getTarget().equals("wear")) {
        Log.v("WEAR:", "COMMAND RECEIVED: " + msg.getCommand());
        Log.v("WEAR:", "TARGET RECEIVED: " + msg.getTarget());
        Log.v("WEAR:", "MESSAGE RECEIVED: " + msg.getMessage());


        if (msg.getCommand().equals("SMS")) {
            Log.v("WEAR:", "SMS COMMAND RAN. " + msg.getMessage());
            // do something
        } else if (msg.getCommand().equals("CODE")) {
            // do something
            Log.v("WEAR:", "CODE RECEIVED:  " + msg.getMessage());

            Main.textCode.setText(msg.getMessage());

        }
    }
}

此代码可以正常工作,直到

Main.textCode.setText(msg.getMessage());

它与NullPointerException崩溃。填充msg.getMessage,因为它根据代码将消息输出到详细日志中。

在我的Main类中,我将textCode声明为TextView,

public static TextView textCode;

然后在onCreate中,我将textCode设置为xml元素:

textCode = (TextView) findViewById(R.id.textCode);

完整错误是:

  

08-20 13:45:41.689 2248-2262 / com.domain.cinesaver E / AndroidRuntime:   致命异常:WearableListenerService       进程:com.domain.cinesaver,PID:2248       显示java.lang.NullPointerException               at com.domain.cinesaver.MessageListener.onMessageReceived(MessageListener.java:50)               在com.google.android.gms.wearable.WearableListenerService $ a $ 2.run(未知   资源)               在android.os.Handler.handleCallback(Handler.java:733)               在android.os.Handler.dispatchMessage(Handler.java:95)               在android.os.Looper.loop(Looper.java:136)               在android.os.HandlerThread.run(HandlerThread.java:61)

2 个答案:

答案 0 :(得分:0)

我建议您向活动发送一个带有一些额外值的新Intent并更改UI。

This question may help you

对于你的活动,接收manifest的新标准需要有这个

<activity android:name=".acitvity"  launchmode="singleTask"/>

当您发送活动所需的意图和价值时,您就是这样。

Intent intent = new Intent(this,acitvity.class);

intent.putExtra("key","value");

getApplicationContext().startActivity(intent);

答案 1 :(得分:0)

您的TextView引用是static,但不应该是static。 TextView依赖于活动的生命周期,因此它依赖于活动的状态,这意味着它应该绑定到对象,而不是绑定到类本身。
删除var getPackagesWithIndex = function(request, indexName, indexValue){ return new Promise(function(resolve, reject){ Package.query(indexValue).usingIndex(indexName).exec( function(err, data){ if (err) return reject(err); // Add the request to the payload data.request_ota = request; resolve(data); }); }) } 限定符并实现一个侦听器接口或类似的东西,以便通知您的活动对象有关此消息的接收。然后,活动本身将决定在收到此消息时该做什么,即当听众被解雇时。