2014-01-26 42 views
0

package com.ravi.seggerclient;如何在android编程中运行联网操作和循环操作

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 Programming.This是我的代码,客户端从一个移动发送大文件到其他使用UDP protocol.Although UDP上不优选这works.It是的一部分我的项目。在我开始使用Android的网络时,我开始知道使用AsyncTask在Android中使用后台线程完成网络,但是当我想要在后台线程中长时间运行循环时,循环包含网络(这就是Asynctask的原因首选),我面临错误 Android无法在未调用Looper.prepare()的线程内创建处理程序。 如何克服这一点以及如何在Android编程中一起运行网络和循环操作。欢迎任何建议。

回答

0

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

AsyncTask被设计成围绕线程和处理程序的助手类,并不构成通用线程框架。理想情况下,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); 

    } 

} 

}

+0

java的导引头,按我的知识在Android的版本在3.0以上,联网操作都被阻挡在主UI线程没有任何权限。我选择了Asynctask for Networking,因为它是一个后台线程 – Ravi4U

+0

是的,如果你在主UI线程中进行网络操作,它将阻止主UI。你已经使用了asynctask,但是asynctask不允许长时间阻塞操作。请参阅官方文档。 –