如何在我的活动添加runOnUiThread() [英] how to add runOnUiThread() in my Activity

查看:104
本文介绍了如何在我的活动添加runOnUiThread()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加了AsyncTask的卸载网络操作后台thread.I需要确保UI操作都在UI thread.So我想用runOnUiThread()在我的活动。

感谢您的帮助

WifiApManager

 公共类WifiApManager {
私人最终WifiManager mWifiManager;

公共WifiApManager(上下文的背景下){
    mWifiManager =(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
}

公共布尔setWifiApEnabled(WifiConfiguration wifiConfig,布尔启用){
    尝试 {
        如果(启用){//禁止在任何情况下的WiFi
            mWifiManager.setWifiEnabled(假);
        }

        方法方法= mWifiManager.getClass()实现getMethod(setWifiApEnabled,WifiConfiguration.class,boolean.class)。
        返程(布尔)method.invoke(mWifiManager,wifiConfig,启用);
    }赶上(例外五){
        Log.e(this.getClass()的toString(),无线上网,E。);
        返回false;
    }
}

公共WIFI_AP_STATE getWifiApState(){
    尝试 {
        方法方法= mWifiManager.getClass()实现getMethod(getWifiApState)。

        INT TMP =((整数)method.invoke(mWifiManager));

        //修正了安卓4.0
        如果(TMP→10){
            TMP = TMP  -  10;
        }

        返回WIFI_AP_STATE.class.getEnumConstants()[TMP]
    }赶上(例外五){
        Log.e(this.getClass()的toString(),无线上网,E。);
        返回WIFI_AP_STATE.WIFI_AP_STATE_FAILED;
    }
}


公共布尔isWifiApEnabled(){
    返回getWifiApState()== WIFI_AP_STATE.WIFI_AP_STATE_ENABLED;
}


公共WifiConfiguration getWifiApConfiguration(){
    尝试 {
        方法方法= mWifiManager.getClass()实现getMethod(getWifiApConfiguration)。
        返程(WifiConfiguration)method.invoke(mWifiManager);
    }赶上(例外五){
        Log.e(this.getClass()的toString(),无线上网,E。);
        返回null;
    }
}


公共布尔setWifiApConfiguration(WifiConfiguration wifiConfig){
    尝试 {
        方法方法= mWifiManager.getClass()实现getMethod(setWifiApConfiguration,WifiConfiguration.class)。
        返回(布尔)method.invoke(mWifiManager,wifiConfig);
    }赶上(例外五){
        Log.e(this.getClass()的toString(),无线上网,E。);
        返回false;
    }
}


公众的ArrayList< ClientScanResult> getClientList(布尔onlyReachables){
    返回getClientList(onlyReachables,10);
}


公众的ArrayList< ClientScanResult> getClientList(布尔onlyReachables,诠释reachableTimeout){
    的BufferedReader BR = NULL;
    ArrayList的< ClientScanResult>结果= NULL;

    尝试 {
        结果=新的ArrayList< ClientScanResult>();
        BR =新的BufferedReader(新的FileReader(的/ proc /净/ ARP));
        串线;
        而((行= br.readLine())!= NULL){
            串[]分裂= line.split(+);

            如果((分裂=空)及!及(splitted.length> = 4)){
                //基本的完整性检查
                串MAC =分裂[3];

                如果(mac.matches(..:..:..:..:..:..)){
                    布尔isReachable = InetAddress.getByName(分裂[0])isReachable(reachableTimeout)。

                    如果(!onlyReachables || isReachable){
                        result.add(新ClientScanResult(分裂[0],劈裂[3],劈裂[5],isReachable));
                    }
                }
            }
        }
    }赶上(例外五){
        Log.e(LOGTAG,e.toString());
    } 最后 {
        尝试 {
            br.close();
        }赶上(IOException异常E){
            Log.e(LOGTAG,e.toString());
        }
    }
返回结果;
}
}
 

connect.java

 公共类连接扩展活动{
WifiApManager wifiApManager;
TextView的电视;
按钮扫描;
@覆盖
保护无效的onCreate(包savedInstanceState){
    // TODO自动生成方法存根
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.connect);
    电视=(TextView中)findViewById(R.id.iptv);
    新的扫描()执行()。
}
公共类扫描扩展AsyncTask的<字符串,整数,字符串> {

公共对象WIFI_SERVICE;
@覆盖
保护无效onProgressUpdate(整数...整数){
     ArrayList的< ClientScanResult>客户端= wifiApManager.getClientList(假);
        tv.setText(WifiApState:+ wifiApManager.getWifiApState()+\ñ\ N);
        tv.append(客户:\ N);
        对于(ClientScanResult clientScanResult:客户端){
            tv.append(#################### \ N);
            tv.append(IPADDR:+ clientScanResult.getIpAddr()+\ N);
            tv.append(设备:+ clientScanResult.getDevice()+\ N);
            tv.append(HWADDR:+ clientScanResult.getHWAddr()+\ N);
            tv.append(isR​​eachable:+ clientScanResult.isReachable()+\ N);
            }
}
@覆盖
        保护无效onPostExecute(字符串结果){
            tv.setText(结果);
        }
@覆盖
保护字符串doInBackground(字符串... PARAMS){
    wifiApManager =新WifiApManager(本);
    //上面一行显示一个错误
    返回null;
}
}
}
 

修改

我要显示处理文本一个TextView

 类扫描扩展AsyncTask的<字符串,太虚,太虚> {
公共上下文的背景下;
ArrayList的< ClientScanResult>客户;
公共扫描(上下文C)//构造带上下文
{
    上下文= C; //初始化上下文变量
}

保护无效doInBackground(字符串... PARAMS){
        wifiApManager =新WifiApManager(上下文); //这里使用的变量
         客户端= wifiApManager.getClientList(假);
        返回null;
}
}
保护无效onPostExecute(无效的结果){
    ArrayList的< ClientScanResult>客户;
    tv.setText(WifiApState:+ wifiApManager.getWifiApState()+\ñ\ N);
    tv.append(客户:\ N);
    对于(ClientScanResult clientScanResult:客户端)//在客户舒错误
 {
            tv.append(#################### \ N);
            tv.append(IPADDR:+ clientScanResult.getIpAddr()+\ N);
            tv.append(设备:+ clientScanResult.getDevice()+\ N);
            tv.append(HWADDR:+ clientScanResult.getHWAddr()+\ N);
            tv.append(isR​​eachable:+ clientScanResult.isReachable()+\ N);
                       }
}
}
 

解决方案
  

我添加了AsyncTask的卸载网络操作后台thread.I需要确保UI操作都在UI thread.So我想用runOnUiThread()在我的活动。

唉!没有!!! 的AsyncTask 的每一个方式运行在 UI线程除了 doInBackground()。所以做你的网络运营中的 doInBackground()和更新 UI onPostExecute() onProgressUpdate()致电 publishProgress() doInBackground ()

不要使用 runOnUiThread()的AsyncTask 。没有任何理由,至少使我知道,使用与的AsyncTask ,因为它已经在 UI线程运行方式。我从来没有见过它做任何事情,但造成麻烦。

您既可以调用 publishProgress()循环和更新的TextView onProgressUpdate()或添加值到的ArrayList 和更新 onProgressUpdate()

请阅读文档几次的。 的AsyncTask 是一个有点棘手,在第一,但一旦你了解它做什么,然后它可以是一个美丽的东西。

修改

创建的实例,你的的AsyncTask 并通过您的活动上下文

 扫描myScan =新的扫描(本); //上下文传递给构造函数
myScan.execute();
 

然后在你的的AsyncTask 创建一个构造函数,并让它接受上下文

 公共类扫描扩展AsyncTask的<字符串,整数,字符串>
{

     公共对象WIFI_SERVICE;
     公共上下文的背景下; //上下文变量

     公共扫描(上下文C)//构造带上下文
     {
         上下文= C; // intialize上下文变量
     }
 

现在使用该变量

  @覆盖
    保护字符串doInBackground(字符串... PARAMS)
    {
        wifiApManager =新WifiApManager(上下文); //这里使用的变量
        返回null;
    }
 

另一个修改

 类扫描扩展AsyncTask的<字符串,太虚,太虚> {
     ArrayList的< ClientScanResult>客户;
     上下文语境;

...

然后初始化你的`clients`在`doInBackground()`

客户端= wifiApManager.getClientList(假);
 

变更 onPostExecute()不接受任何

 保护无效onPostExecute(无效的结果){
 

和把你的code,更新了的TextView 在那里。

I added the AsyncTask to offload network operations to a background thread.I need to make sure the UI operations are on the UI thread.So i want to Use runOnUiThread() in my Activity.

Thanks for your help

WifiApManager

public class WifiApManager {
private final WifiManager mWifiManager;

public WifiApManager(Context context) {
    mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}

public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
    try {
        if (enabled) { // disable WiFi in any case
            mWifiManager.setWifiEnabled(false);
        }

        Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
        return (Boolean) method.invoke(mWifiManager, wifiConfig, enabled);
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "wifi", e);
        return false;
    }
}

public WIFI_AP_STATE getWifiApState() {
    try {
        Method method = mWifiManager.getClass().getMethod("getWifiApState");

        int tmp = ((Integer)method.invoke(mWifiManager));

        // Fix for Android 4
        if (tmp > 10) {
            tmp = tmp - 10;
        }

        return WIFI_AP_STATE.class.getEnumConstants()[tmp];
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "wifi", e);
        return WIFI_AP_STATE.WIFI_AP_STATE_FAILED;
    }
}


public boolean isWifiApEnabled() {
    return getWifiApState() == WIFI_AP_STATE.WIFI_AP_STATE_ENABLED;
}


public WifiConfiguration getWifiApConfiguration() {
    try {
        Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
        return (WifiConfiguration) method.invoke(mWifiManager);
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "wifi", e);
        return null;
    }
}


public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
    try {
        Method method = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
        return (Boolean) method.invoke(mWifiManager, wifiConfig);
    } catch (Exception e) {
        Log.e(this.getClass().toString(), "wifi", e);
        return false;
    }
}


public ArrayList<ClientScanResult> getClientList(boolean onlyReachables) {
    return getClientList(onlyReachables, 10);
}


public ArrayList<ClientScanResult> getClientList(boolean onlyReachables, int reachableTimeout) {
    BufferedReader br = null;
    ArrayList<ClientScanResult> result = null;

    try {
        result = new ArrayList<ClientScanResult>();
        br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;
        while ((line = br.readLine()) != null) {
            String[] splitted = line.split(" +");

            if ((splitted != null) && (splitted.length >= 4)) {
                // Basic sanity check
                String mac = splitted[3];

                if (mac.matches("..:..:..:..:..:..")) {
                    boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);

                    if (!onlyReachables || isReachable) {
                        result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
                    }
                }
            }
        }
    } catch (Exception e) {
        Log.e(LOGTAG, e.toString());
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            Log.e(LOGTAG, e.toString());
        }
    }
return result;
}
}

connect.java

public class connect extends Activity{
WifiApManager wifiApManager;
TextView tv;
Button scan;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connect);
    tv =(TextView) findViewById(R.id.iptv);
    new scan().execute();
}
public class scan extends AsyncTask<String, Integer, String> {

public Object WIFI_SERVICE;
@Override
protected void onProgressUpdate(Integer...integers)  {
     ArrayList<ClientScanResult> clients = wifiApManager.getClientList(false);
        tv.setText("WifiApState: " + wifiApManager.getWifiApState() + "\n\n");
        tv.append("Clients: \n");
        for (ClientScanResult clientScanResult : clients) {
            tv.append("####################\n");
            tv.append("IpAddr: " + clientScanResult.getIpAddr() + "\n");
            tv.append("Device: " + clientScanResult.getDevice() + "\n");
            tv.append("HWAddr: " + clientScanResult.getHWAddr() + "\n");
            tv.append("isReachable: " + clientScanResult.isReachable()+ "\n");
            }
}
@Override
        protected void onPostExecute(String result){
            tv.setText(result);             
        }
@Override
protected String doInBackground(String... params) {
    wifiApManager = new WifiApManager(this);
    // the above line shows a Error
    return null;
}
}
}

EDIT

I want to Display the processed text in a TextView

class scan extends AsyncTask<String, Void, Void> { 
public Context context;
ArrayList<ClientScanResult> clients;
public scan(Context c)  // constructor to take Context
{
    context = c;   // Initialize your Context variable
}

protected Void doInBackground(String... params) {
        wifiApManager = new WifiApManager(context);  // use the variable here
         clients = wifiApManager.getClientList(false);
        return null;
}
}           
protected void onPostExecute(Void result){
    ArrayList<ClientScanResult> clients;
    tv.setText("WifiApState: " + wifiApManager.getWifiApState() + "\n\n");
    tv.append("Clients: \n");
    for (ClientScanResult clientScanResult : clients)//showin error in clients
 {
            tv.append("####################\n");
            tv.append("IpAddr: " + clientScanResult.getIpAddr() + "\n");
            tv.append("Device: " + clientScanResult.getDevice() + "\n");
            tv.append("HWAddr: " + clientScanResult.getHWAddr() + "\n");
            tv.append("isReachable: " + clientScanResult.isReachable()+ "\n");
                       }
}
}

解决方案

I added the AsyncTask to offload network operations to a background thread.I need to make sure the UI operations are on the UI thread.So i want to Use runOnUiThread() in my Activity.

Ugh! No!!! Every method of AsyncTask runs on the UI Thread except for doInBackground(). So do your network operations in doInBackground() and update the UI in onPostExecute() or in onProgressUpdate() by calling publishProgress() from doInBackground().

Do not use runOnUiThread() with AsyncTask. There is no reason, at least known to me, to use that with AsyncTask since it has methods that already run on the UI Thread. I have never seen it do anything but cause trouble.

You can either call publishProgress() from your loop and update your TextView in onProgressUpdate() or add the values to an ArrayList and update in onProgressUpdate().

Please read the docs several times. AsyncTask is a bit tricky at first but once you learn what it does then it can be a beautiful thing.

Edit

Create an instance of your AsyncTask and pass your Activity Context to it

Scan myScan = new scan(this); // pass the context to the constructor
myScan.execute();

Then create a constructor in your AsyncTask and have it accept a Context.

public class scan extends AsyncTask<String, Integer, String> 
{

     public Object WIFI_SERVICE;
     public Context context;   // Context variable

     public scan(Context c)  // constructor to take Context
     {
         context = c;   // intialize your Context variable
     }

Now use that variable

    @Override
    protected String doInBackground(String... params) 
    {
        wifiApManager = new WifiApManager(context);  // use the variable here
        return null;
    }

Another Edit

class scan extends AsyncTask<String, Void, Void> {
     ArrayList<ClientScanResult> clients;
     Context context;

...

then initialize your `clients` in `doInBackground()`

clients = wifiApManager.getClientList(false);

change onPostExecute() to not accept anything

protected void onPostExecute(Void result){

and put your code that updates the TextView in there.

这篇关于如何在我的活动添加runOnUiThread()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆