2014-01-26 45 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不允許長時間阻塞操作。請參閱官方文檔。 –