清单中的Andr​​oid网络设备 [英] Listing of the Network Devices in Android

查看:124
本文介绍了清单中的Andr​​oid网络设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相似或相同的问题已经回答了<一个href=\"http://stackoverflow.com/questions/16478969/android-listen-to-devices-over-socket-and-create-their-list\">here

我创建一个Android应用程序,它发送广播消息到网络上,prepares设备响应后面的列表。

I am creating an Android App, which sends a broadcast message to the network and prepares a list of devices responding back.

我现在做什么:

我创建了一个活动 DeviceManagerWindow.java 它调用线程 Sender.java
Sender.java 是负责发送广播消息。

I created an Activity Class DeviceManagerWindow.java which calls a thread Sender.java. Sender.java is responsible for sending the broadcast message.

然后 DeviceManagerWindow.java 调用另一个线程负责监听响应回设备。在设备回覆我们将在活动只要设备响应后面列出。对于我有一个 TableLayout 名为 DEVICELIST

Then the DeviceManagerWindow.java calls another thread which is responsible for listening to the devices responding back. The devices responding back will be listed in the Activity as soon as the device responds back. For that I have a TableLayout named deviceList.

什么code我已经写:

What code I have written:

DeviceManagerWindow.java 这个方法被调用时,搜索按钮是pressed

public void searchDevice(View v) throws IOException, InterruptedException
{
    //Log.v("TableLayout:",view.toString());
    sendMulticastFlyport = new Thread(new FlyportSender(MAC));
    sendMulticastFlyport.start();
    new Thread()
    {
        public void run()
        {
            MulticastSocket socketComputer=null;
            try
            {
                socketComputer = new MulticastSocket(WifiConstants.COMPUTER_RECV_PORT);
                socketComputer.joinGroup(InetAddress.getByName(WifiConstants.COMPUTER_NETWORK_ADDR));
                socketComputer.setSoTimeout(1*60*1000);
                byte[] inBufComputer = new byte[1024];
                DatagramPacket inPacketComputer = new DatagramPacket(inBufComputer, inBufComputer.length);

                while(true)
                {
                    System.out.println("Listening...");
                    socketComputer.receive(inPacketComputer);
                    System.out.println("Received");
                    String msg = new String(inBufComputer, 0, inPacketComputer.getLength());
                    DeviceInformation device = new DeviceInformation(1, msg, inPacketComputer.getAddress().toString());

                    addDevice(device, false, 1);

                    Log.v("Received:","Received Computer From :" + inPacketComputer.getAddress() + " Msg : " + msg);
                    //System.out.write(inPacket.getData(),0,inPacket.getLength());
                    System.out.println();
                    Thread.sleep(2000);
                }
            }
            catch(Exception e)
            {
                Log.v("Exception:","During Receiving Computer: "+e.toString());
                try
                {
                    addDevice(null, true, 1);
                }
                catch (IOException e1)
                {
                    Log.v("Exception:", "Computer End Error: " +e1);
                }
            }
            finally
            {
                socketComputer.close();
            }
        }
    }.start();

以下code创建一个列表:

public void addDevice(DeviceInformation device, boolean bool, int type) throws IOException
{
    TableLayout tb = (TableLayout) findViewById(R.id.DeviceList);
    Log.v("addDevice","Called");
    if(bool)
    {
        LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        TableRow tr = new TableRow(getApplicationContext());
        TextView tv = new TextView(getApplicationContext());
        System.out.println(tb);
        tv.setLayoutParams(layout);
        tr.setLayoutParams(layout);
        String message;
        Log.v("addDevice","Device Timeout");
        switch(type)
        {
            case 1:
                computerEnd=true;
                break;
            case 2:
                raspberryEnd=true;
                break;
            case 3:
                flyportEnd=true;
                break;
        }
        if(computerEnd && raspberryEnd && flyportEnd)
        {
            if(rowCounter>0)
            {
                message = "No More Devices";
            }
            else
            {
                message = "No Devices Found"; 
            }
            tv.setText(message);
            tv.setTextColor(Color.WHITE);
            if(rowCounter%2==0)
            {
                tr.setBackgroundColor(Color.DKGRAY);
            }
            else
            {
                tr.setBackgroundColor(Color.GRAY);
            }
            tv.setVisibility(1);
            tr.addView(tv);
            tb.addView(tr);
        }
    }
    else
    {   
        LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        TableRow tr = new TableRow(getApplicationContext());
        TextView tv = new TextView(getApplicationContext());

        tv.setLayoutParams(layout);
        tr.setLayoutParams(layout);

        Log.v("addDevice","Received");
        String textToDisplay = device.getDeviceTypeString()+"\n"+device.getIPAddress(); //Write the text to display
        tv.setText(textToDisplay);
        tv.setTextColor(Color.WHITE);
        Drawable img;
        if(device.getDeviceType()==1)
        {
            img = getApplicationContext().getResources().getDrawable(R.drawable.pc);
        }
        else if(device.getDeviceType()==2)
        {
            img = getApplicationContext().getResources().getDrawable(R.drawable.raspberry);
        }
        else
        {
            img = getApplicationContext().getResources().getDrawable(R.drawable.flyport);
        }
        img.setBounds(0,0,70,45);
        tv.setCompoundDrawables(null, null, img, null);
        tv.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

            }
        });
        if(rowCounter%2==0)
        {
            tr.setBackgroundColor(Color.DKGRAY);
        }
        else
        {
            tr.setBackgroundColor(Color.GRAY);
        }
        rowCounter++;
        Log.v("Result","Device Added");
    }
}

现在它显示我的logcat的一个错误:

Now it is showing me an error in the logCat as:

05-11 22:01:10.165: E/AndroidRuntime(13873): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

我从这个想通了,只是UIThread被允许访问所创建的视图。

previously我曾尝试:

Previously I had tried:

new Thread()
{
    public void run()
    {
        runOnUiThread(){
        MulticastSocket socketComputer=null;
        try
        {
            ....        
            ....
            ....
    }
}

和那个时候,我收到了一个错误:

And that time I received an error:

主线程不能访问网络

这之前,我曾试图用它是从 Receiving.java 发文件名为同步方法。但它也给了没有创造列表的错误。

Before that I had tried to use synchronized methods which was called from the Receiving.java Thread File. but It also gave an error of not creating the list.

我已经尝试了所有可能的方式。

I have tried all possible ways.

现在什么我对子级做?

推荐答案

您理解了它的权利。现在,你可以学习或者使用一个处理程序将信息传递到UI线程(见的http://www.techotopia.com/index.php/A_Basic_Overview_of_Android_Threads_and_Thread_handlers)或AsyncTask的(见 http://developer.android.com/reference/android/os /AsyncTask.html )。

You figured it out right. Now you can learn to either use a Handler to pass information to the UI thread (see http://www.techotopia.com/index.php/A_Basic_Overview_of_Android_Threads_and_Thread_handlers) or AsyncTask (see http://developer.android.com/reference/android/os/AsyncTask.html).

我个人preFER AsyncTask的。您可以粘贴code其中执行搜索到doInBackground()方法(不需要使用一个单独的线程,doInBackground()已经做了你)并粘贴UI相关的code(列表创建code)进入onPostExecute()方法。搜索的AsyncTask的进一步实例,如果它不是足够清楚它从链路的工作原理。

I personally prefer AsyncTask. You can paste the code which performs the search into the doInBackground() method (not need to use a separate thread, doInBackground() already does that for you) and paste the UI-related code (the list creation code) into the onPostExecute() method. Search for further examples of AsyncTask if it is not sufficiently clear how it works from the link.

编辑:如果您想您的设备搜索code无限期运行,那么你不得不求助于处理程序,为的AsyncTask预计doInBackground()方法来运行onPostExecute之前完成()。看哪个选项更适合您的需求。

If you intend your device search code to run indefinitely, then you have to resort to Handler, as AsyncTask expects the doInBackground() method to finish before running onPostExecute(). See which option better suits your needs.

这篇关于清单中的Andr​​oid网络设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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