如何在android编程中一起运行网络操作和循环操作

时间:2014-01-26 16:10:42

标签: java android multithreading sockets

package com.ravi.seggerclient;

public class MainActivity extends Activity 
{

    EditText text,text2;
    String selectedImagePath,ll=null;
    Timer ravi;
    static DatagramSocket clsoc;
    static InetAddress ip;
    static File ff;
    byte[] arr = null;
    static int len,totpac;
    static RandomAccessFile raf;
    static FileChannel chan;
    static int buffsize;
    static int i=0,id=0,numRead=0;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    text = (EditText)findViewById(R.id.editText1);
    text2 = (EditText)findViewById(R.id.editText2);

    final  String state = Environment.getExternalStorageState();
     ((Button) findViewById(R.id.button1))
        .setOnClickListener(new OnClickListener()
        {
            public void onClick(View arg0)
            {
                try
                {
                    if (Environment.MEDIA_MOUNTED.equals(state)) 
                    {
                        String  root =                           Environment.getExternalStorageDirectory().toString();
                        selectedImagePath = root +"/Nenjodu.mp4";                                ff = new File(selectedImagePath);

                        text.setText(selectedImagePath+"File Is Found"+"File length"+ff.length());
                    }
                }
            catch(Exception e)
            {
                text.setText(""+e);
            }
            }
    });

    ((Button) findViewById(R.id.button2))
    .setOnClickListener(new View.OnClickListener()
    {
         public void onClick(View arg0)
         {

        try
        {

        Ravii rav = new Ravii();
        ll="NOT SENT";
        ll = rav.execute().get();
        text2.setText(""+ll);

        }
        catch(Exception e)
        {
            Log.d("Error in Sending",""+e);
        }


            }

       });

}



private class Ravii extends AsyncTask<String,Void,String>
{

@Override
    protected String doInBackground(String... params)
    {
        // TODO Auto-generated method stub
        try{

            clsoc = new DatagramSocket();
            ip = InetAddress.getByName("192.168.137.1");
                len = (int)ff.length();
                totpac = len/(30*1024)+1;

                buffsize = 30;
                String ss ="#"+totpac+"&";

                Log.d("No of Packets",""+totpac);
                byte[] fsize = new byte[1024];
                fsize = ss.getBytes();


                DatagramPacket dp = new DatagramPacket(fsize,fsize.length,ip,8000);
            clsoc.send(dp);
            raf = new RandomAccessFile(ff,"rw");
                chan = raf.getChannel();
                while(numRead>=0)
                {
                    ByteBuffer buf = ByteBuffer.allocate(1024*buffsize);
                    if(i==id)
                    numRead = chan.read(buf);
                    if((numRead>0)&&(i==id))
                    {
                        arr = new byte[numRead];
                        System.arraycopy(buf.array(),0,arr,0,numRead);
                        DatagramPacket sp = new DatagramPacket(arr,arr.length,ip,8000);
                        clsoc.send(sp);
                        i++;
                        byte[] receiveData = new byte[1024];
                        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                        clsoc.receive(receivePacket);
                        String mod = new String(receivePacket.getData());
                        System.out.println("\n" + mod);
                        id=Integer.parseInt(mod.substring(mod.indexOf("#") + 1, mod.indexOf("&")));

                    }
                    else if((numRead>0)&&(i!=id))
                    {
                        i--;

                        DatagramPacket sp = new DatagramPacket(arr,arr.length,ip,8000);
                        clsoc.send(sp);
                        text2.setText("ReSent "+i+" packet");
                        i++;
                        byte[] receiveData = new byte[1024];
                        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                        clsoc.receive(receivePacket);
                        String mod = new String(receivePacket.getData());
                        id=Integer.parseInt(mod.substring(mod.indexOf("#") + 1, mod.indexOf("&")));
                    }
                    else
                    {
                        Toast.makeText(getApplicationContext(),"Nothing to Send" , Toast.LENGTH_SHORT).show();
                    }
                }
                return "SuccessFul";
        }
        catch(Exception e)
        {
        Log.d("Exception in the Client Sending",""+e);

           }

         }
    }
}

您好我是Android编程的新手。这是我的代码,客户端使用UDP协议从一个移动设备向其他移动设备发送大文件。虽然UDP不是这项工作的首选。它是我项目的一部分。这里当我在Android中启动Networking时,我开始知道网络是使用AsyncTask在Android中使用Background线程完成的,但是当我想在后台线程中长时间运行循环时,循环包括网络(这是Asynctask首选的原因),我我正面临一个错误 Android无法在未调用Looper.prepare()的线程内创建处理程序。 如何克服这一点以及如何在Android编程中一起运行网络和循环操作。欢迎任何建议。

1 个答案:

答案 0 :(得分:0)

AsyncTask可以正确,轻松地使用UI线程。该类允许执行后台操作并在UI线程上发布结果,而无需操纵线程和/或处理程序。

  

AsyncTask旨在成为Thread和Handler的辅助类,并不构成通用的线程框架。理想情况下,AsyncTasks应该用于短操作(最多几秒钟。)

避免使用AsyncTask进行长时间阻止网络操作。而是使用基本的线程

私有类Ravii扩展了Thread {

public void run() {
    try {

        clsoc = new DatagramSocket();
        ip = InetAddress.getByName("192.168.137.1");
        len = (int) ff.length();
        totpac = len / (30 * 1024) + 1;

        buffsize = 30;
        String ss = "#" + totpac + "&";

        Log.d("No of Packets", "" + totpac);
        byte[] fsize = new byte[1024];
        fsize = ss.getBytes();

        DatagramPacket dp = new DatagramPacket(fsize, fsize.length, ip,
                8000);
        clsoc.send(dp);
        raf = new RandomAccessFile(ff, "rw");
        chan = raf.getChannel();
        while (numRead >= 0) {
            ByteBuffer buf = ByteBuffer.allocate(1024 * buffsize);
            if (i == id)
                numRead = chan.read(buf);
            if ((numRead > 0) && (i == id)) {
                arr = new byte[numRead];
                System.arraycopy(buf.array(), 0, arr, 0, numRead);
                DatagramPacket sp = new DatagramPacket(arr, arr.length, ip,
                        8000);
                clsoc.send(sp);
                i++;
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(
                        receiveData, receiveData.length);
                clsoc.receive(receivePacket);
                String mod = new String(receivePacket.getData());
                System.out.println("\n" + mod);
                id = Integer.parseInt(mod.substring(mod.indexOf("#") + 1,
                        mod.indexOf("&")));

            } else if ((numRead > 0) && (i != id)) {
                i--;

                DatagramPacket sp = new DatagramPacket(arr, arr.length, ip,
                        8000);
                clsoc.send(sp);
                text2.setText("ReSent " + i + " packet");
                i++;
                byte[] receiveData = new byte[1024];
                DatagramPacket receivePacket = new DatagramPacket(
                        receiveData, receiveData.length);
                clsoc.receive(receivePacket);
                String mod = new String(receivePacket.getData());
                id = Integer.parseInt(mod.substring(mod.indexOf("#") + 1,
                        mod.indexOf("&")));
            } else {
                Toast.makeText(getApplicationContext(), "Nothing to Send",
                        Toast.LENGTH_SHORT).show();
            }
        }
        return "SuccessFul";
    } catch (Exception e) {
        Log.d("Exception in the Client Sending", "" + e);

    }

}

}