片段中的Android AsynTask方法

时间:2015-12-17 08:57:05

标签: android android-fragments android-asynctask

我目前正在使用可以使用Android手机控制的arduino。我正试图用手机点亮一个LED。我尝试了它,它的工作原理。问题是代码是在一个活动中。我正在使用tabhost和pageViewer从应用程序中找到一个片段中的灯光按钮。如何使用片段调用方法Asyntask和按钮的Onclicklistener来点亮led。

这里是MainActivity的代码。

{{1}}

请帮助

1 个答案:

答案 0 :(得分:0)

你的片段可以是这样的

public class Fragment1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    view = inflater.inflate(R.layout.your_activity, container, false);      

    Button led3 = (Button) v.findViewById(R.id.Led3);

    led3.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
            /* button is led 3 */
                new Background_get("led3=1").execute();
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                new Background_get("led3=0").execute();
            }
            return true;
        }
    });

    return view;
}

您可以直接直接访问asynctask类

 public class Background_get extends AsyncTask<Void, Void, Void> {

    String param;

    public Background_get(String param){
        this.param = param;
    }

    @Override
    protected Void doInBackground(Void... params) {
        try {
            /* Change the IP to the IP you set in the arduino sketch */
            URL url = new URL("http://192.168.1.177/?" + param);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder result = new StringBuilder();
            String inputLine;
            while ((inputLine = in.readLine()) != null)
            result.append(inputLine).append("\n");

            in.close();
            connection.disconnect();                

        } catch (IOException e) {
        e.printStackTrace();
        }           
    }

}