android - 如何在android中使用runnable

标签 android runnable

你好,我是 Java Android 开发的新手,我想知道如何在 Android 中使用 Runnable。它似乎对我不起作用。这是我的源代码:

MainTest.java

package com.heeere.androiddnssd.discovery;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainTest extends Activity {

    android.net.wifi.WifiManager.MulticastLock lock;
    private Discovery discovery = new Discovery(this); 
    private TextView textView;

    /** Called when the activity is first created. */
    @SuppressLint("NewApi") @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView)this.findViewById(R.id.text);

        android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) getSystemService(android.content.Context.WIFI_SERVICE);
        lock = wifi.createMulticastLock("mylockthereturn");
        lock.setReferenceCounted(true);
        lock.acquire();

    }

    public void updateView () {
        String msg = discovery.getMsg();
        textView.setText(msg);
    }

    @SuppressLint("NewApi") @Override
    protected void onStop() {
        discovery.stop();
        lock.release();
        super.onStop();
    }


}

Discovery.java

package com.heeere.androiddnssd.discovery;

import java.io.IOException;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceListener;

public class Discovery {


    private String type = "_ikunet._tcp.local.";
    private String msg="";
    private JmDNS jmdns = null;
    private ServiceListener listener = null;
    private MainTest maintest;
    android.os.Handler handler = new android.os.Handler();

    public Discovery (MainTest maintest) {
        this.maintest = maintest;
        setUp();
    }

    private void setUp() {

        try {
            jmdns = JmDNS.create();
            jmdns.addServiceListener(type, listener = new ServiceListener() {

                public void serviceResolved(ServiceEvent ev) {
                    msg = msg + ev.getInfo().getName()+ "\n";
                    update();
                }

                public void serviceRemoved(ServiceEvent ev) {
                }

                public void serviceAdded(ServiceEvent event) {
                    jmdns.requestServiceInfo(event.getType(), event.getName(), 1);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
    }

    public String getMsg() {
        return msg;
    }

    private void update() {
        handler.postDelayed(new Runnable() {
            public void run() {
                maintest.updateView();
            }
        }, 1);
    }


    public void stop() {
        if (jmdns != null) {
            if (listener != null) {
                jmdns.removeServiceListener(type, listener);
                listener = null;
            }
            jmdns.unregisterAllServices();
            try {
                jmdns.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jmdns = null;
        }
    }

}

ma​​in.xml

<?xml version="1.0" encoding="utf-8"?>

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scroller"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              android:orientation="vertical"
              android:scrollbars="vertical"
              android:fadeScrollbars="true"
              android:isScrollContainer="true">
    <TextView  
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="Hello World, Android Discovery" />
    <TextView 
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a TextView" />
    <Button 
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a Button" />
    </LinearLayout>
</ScrollView>

serviceResolved 在应用程序启动一段时间后从 Discovery 类执行,并且应该更新 textview(来自 MainTest类)。但这不会发生。我该如何解决这个问题?我认为这可能是 Runnable 问题。

最佳答案

试试这个

private void update() {
    final Runnable r = new Runnable() {
        public void run() {
            maintest.updateView();
            handler.postDelayed(this, 1000);
        }
    };
    handler.postDelayed(r, 1000);
}

但我会向您推荐这个:

private void update() {
new Thread() {
    public void run() {
        while (true) {
            runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                      maintest.updateView();
                 }
            });
            Thread.sleep(1000);
        } 
    }
}.start();
}

关于android - 如何在android中使用runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12366448/

相关文章:

android - 如何为多个移动平台创建软件?

android - 使用自定义动画显示 Activity

android - 如何从父类调用子类的方法?

Java点对点线程模型,大家等待Job

Android从递归算法更新ui

java - 自定义 ArrayList 序列化

android - 在 UI 线程上加载和创建 AsyncTask 有什么区别?

java - 可运行崩溃中的 HTTPPost

java - While 循环变量赋值给 Runnable

java - 在 Java 中,如何在每个线程中运行不同的方法?