如何将此代码更改为AsyncTask?

时间:2018-05-27 22:53:12

标签: android

我尝试在Java(pc)和Android之间进行Socket程序.APP从gallery中选择一个图像。显示我选择的图像。然后用socket发送到Java。我想把这个代码更改为AsyncTask但是我无法做到。我阅读了关于AsyncTask的例子,但我怎样才能改变这段代码。任何人都可以帮我解决这个问题吗?

public class SendfileActivity extends Activity   {
    /** Called when the activity is first created. */

    private static final int SELECT_PICTURE = 1;

    private String selectedImagePath;
    private ImageView img;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        System.out.println("34");
        img = (ImageView) findViewById(R.id.ivPic);
        System.out.println("36");
        ((Button) findViewById(R.id.bBrowse))
                .setOnClickListener(new OnClickListener() {
                    public void onClick(View arg0) {
                        System.out.println("40");
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(
                                Intent.createChooser(intent, "Select Picture"),
                                SELECT_PICTURE);
                        System.out.println("47");
                    }
                });
        ;
        System.out.println("51");
        Button send = (Button) findViewById(R.id.bSend);
        final TextView status = (TextView) findViewById(R.id.tvStatus);

        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Socket sock;
                try {
                    sock = new Socket("192.168.0.3", 27015);
                    System.out.println("Connecting...");

                    // sendfile
                    File myFile = new File (selectedImagePath);
                    byte [] mybytearray  = new byte [(int)myFile.length()];
                    FileInputStream fis = new FileInputStream(myFile);
                    BufferedInputStream bis = new BufferedInputStream(fis);
                    bis.read(mybytearray,0,mybytearray.length);
                    OutputStream os = sock.getOutputStream();
                    System.out.println("Sending...");
                    os.write(mybytearray,0,mybytearray.length);
                    os.flush();

                    sock.close();
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }




            }
        });
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                TextView path = (TextView) findViewById(R.id.tvPath);
                path.setText("Image Path : " + selectedImagePath);
                img.setImageURI(selectedImageUri);
            }
        }
    }

    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

}

2 个答案:

答案 0 :(得分:0)

此处的套接字通信不需要

AsyncTask,因为没有触及UI元素。相反,您可以使用ThreadRunnable

如果在客户端和服务器之间传递了持续的消息,那么可以使用HandlerThreadHandler的组合来实现它。 对于简单的线程使用,您可以:

    class SocketThread implements Runnable {

    @Override
    public void run() {

        Socket sock;
        try {
            sock = new Socket("192.168.0.3", 27015);
            System.out.println("Connecting...");

            // sendfile
            File myFile = new File(selectedImagePath);
            byte[] mybytearray = new byte[(int) myFile.length()];
            FileInputStream fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);
            bis.read(mybytearray, 0, mybytearray.length);
            OutputStream os = sock.getOutputStream();
            System.out.println("Sending...");
            os.write(mybytearray, 0, mybytearray.length);
            os.flush();

            sock.close();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

并且可以在发送按钮的onClick

上启动此运行
    new Thread(new SocketThread()).start();

我希望这会有所帮助

答案 1 :(得分:0)

如果您确实想使用AsyncTask:

 public class ImagePicker extends AsyncTask<String, String, String> {
     protected String doInBackground(String imgPath) {
       //Your socket code here from the onclick
     }

protected void onProgressUpdate(String progressString) {
       System.out.println("Sending...");
     }

     protected void onPostExecute(String result) {
// print result
      sock.close();
     }
 }

然后你可以在你的onclick中执行任务:

send.setOnClickListener{
    new ImagePicker().execute(imgPathString);
}