Using Libcurl third-party libraries for Android asynchronous tasks

Source: Internet
Author: User

This article takes the Cocos2d-x Libcurl from the previous blog to be packaged separately to Android

On this basis, further use has been made:

1) Add Libcurl Async method

2) Implement Android asynchronous task

Directly below the code:

1 "jni first.c:first.h no change, first.c add the following code, remember that C variables must be declared method function start

/* Copyright (C) The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License") ; * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. * */#include "first.h" int first (int x, int y) {return x + y;} #define Multi_curl_num 3char* URL = "http://www.baidu.com"; char* PROXY = ""; unsigned int TIMEOUT = 10000;char* Urla[3] = { "Http://www.baidu.com", "http://www.cocoachina.com/bbs/read.php?tid=228963", "http://www.cnblogs.com/zhaoyl/p/ 4001151.html "};//Async method gets the return data size_t curl_writer (void* buffer,size_t size,size_t count,void* stream) {//    std::string* PStream = static_cast<std::string*> (stream);//(*pstream). Append ((char*) buffer,size * count);//    Log ("pstream=%s", PStream); return size*count;} To increase the URL request, Async is essentially a combination of multiple synchronization requests curl* Curl_easy_handler (const char* surl,const char* sproxy,char* srsp,unsigned int uitimeout    ) {curl* CURL = Curl_easy_init ();    Curl_easy_setopt (curl, Curlopt_url,surl);    Curl_easy_setopt (curl, curlopt_nosignal,1);    if (Uitimeout > 0) {curl_easy_setopt (curl, curlopt_timeout_ms,uitimeout);    } if (sproxy[0]!= ') {curl_easy_setopt (curl, curlopt_proxy,sproxy);    } curl_easy_setopt (curl, curlopt_writefunction,curl_writer);    Curl_easy_setopt (curl, CURLOPT_WRITEDATA,&AMP;SRSP);//log ("Curl_write =%lu", sizeof (SRSP)); return curl;}    Select method, which selects the currently writable file int curl_multi_select (curlm* curl_m) {int ret = 0;    int idx1 = 0;    struct Timeval timeout_tv;    Fd_set Fd_read;    Fd_set Fd_write;    Fd_set fd_except;    int max_fd =-1;   int Ret_code; Fd_zero (&fd_read);    Fd_zero (&fd_write);    Fd_zero (&fd_except);    Timeout_tv.tv_sec = 60;    timeout_tv.tv_usec = 0;    Curl_multi_fdset (Curl_m, &fd_read, &fd_write, &fd_except, &AMP;MAX_FD);//log ("MAX_FD =%d", max_fd);    if (max_fd = =-1) {return-1;    }//Ret_code =:: Select (max_fd+1, &fd_read, &fd_write, &fd_except, &AMP;TIMEOUT_TV); Ret_code = Select (Max_fd+1, &fd_read, &fd_write, &fd_except, &AMP;TIMEOUT_TV);//log ("Ret_code =%d", Ret_co    DE);            Switch (ret_code) {case-1: ret =-1;        Break            Case 0:default:ret = 0;    Break } return ret;}    Async Method Entry int Curl_multi_demo (int num,curlcode* result) {int idx;static int count = 0;    curlm* curl_m = Curl_multi_init ();    char* Rsparray[num];    int running_handles = 0;    int msgs_left;    curlmsg* msg;//int S[num];    curl* Curlarray[num];       for (idx = 0; idx < num; ++idx) { CURLARRAY[IDX] = NULL;        CURLARRAY[IDX] = Curl_easy_handler (URL, PROXY, Rsparray[idx], TIMEOUT);        if (curlarray[idx] = = NULL) {return-1;    } curl_multi_add_handle (Curl_m, Curlarray[idx]);    }//log ("Running_handles out =%d", running_handles); while (Curlm_call_multi_perform = = Curl_multi_perform (curl_m, &running_handles)) {//log ("Running_handles =%    D ", running_handles);    }//log ("Running_handles out =%d", running_handles);            while (Running_handles) {if ( -1 = = Curl_multi_select (curl_m)) {//log ("select Error");        Break                }else{while (Curlm_call_multi_perform = = Curl_multi_perform (curl_m, &running_handles)) {//            Log ("select:%d", running_handles);    }}//log ("Select:%d", running_handles);        } while (msg = Curl_multi_info_read (Curl_m, &msgs_left))) {if (Curlmsg_done = = msg->msg);   {         int idx;            for (idx = 0; idx < num; ++idx) {if (Msg->easy_handle = = Curlarray[idx]) break;            } if (idx = = num) {//log ("Curl not Found"); }else{//log ("curl [%d] completed with status:%d", idx,msg->data.result);//Log ("RSP:%s"            , Rsparray[idx]); result[count++] = msg->data.result;//will find the result state passed in to result array, the array is a pointer}} for (idx = 0; idx < num;    ++IDX) {Curl_multi_remove_handle (curl_m, Curlarray[idx]);    } for (idx = 0; idx < num; ++idx) {curl_easy_cleanup (curlarray[idx]);    } curl_multi_cleanup (Curl_m); return 0;}    Synchronization method Entry int curl_easy_demo (int num) {int idx = 0;    char* Rsparray[num];        for (idx = 0; idx < num; ++idx) {curl* CURL = Curl_easy_handler (URL, PROXY, Rsparray[idx], TIMEOUT); Curlcode code = curl_easy_perform (curl);//log ("curl [%d] completed with Status:%d ", Idx,code);    Curl_easy_cleanup (curl); } return 0;}

2 "Second.c of the JNI

#include "first.h" #include <jni.h> #include <curl/curl.h> #include <stdio.h> #include <stdlib.h > #include <sys/time.h> #include <unistd.h>//extern "C" Jintjava_com_example_libdemo_mainactivity_add                                      (jnienv* env, jobject This, Jint x, Jint y) {/*//libcurl synchronous method case curl* curl;    Curlcode Res;curl = Curl_easy_init (); if (NULL = = Curl) {return first (1,999);}    Curl_easy_setopt (Curl, Curlopt_url, "http://www.baidu.com");    Curl_easy_setopt (curl, curlopt_readfunction,null);    Curl_easy_setopt (curl, curlopt_nosignal,1);    Curl_easy_setopt (curl, curlopt_connecttimeout,20);    Curl_easy_setopt (curl, curlopt_timeout,20);    res = curl_easy_perform (curl);    Curl_easy_cleanup (curl); *///libcurl Async method Case Curlcode Result[3];int sum;    Gettimeofday (&AMP;BEGIN_TV, NULL);    Curl_multi_demo (3,result);    Gettimeofday (&AMP;END_TV, NULL); Long eclapsed = (end_tv.tv_SEC-BEGIN_TV.TV_SEC) *1000 + (end_tv.tv_usec-begin_tv.tv_usec)/1000;//log ("eclapsed time:%ld MS", eclapsed);    sum = (int) result[0] + (int) result[1]; Return First (sum, (int) result[2]);}
3 "Mainactivity.java of SRC

Package Com.example.libdemo;import Org.apache.http.client.httpclient;import Org.apache.http.impl.client.defaulthttpclient;import Android.os.asynctask;import Android.os.Bundle;import Android.support.v7.app.actionbaractivity;import Android.util.log;import Android.view.menu;import Android.view.menuitem;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.progressbar;import Android.widget.textview;public class MainActivity Extends Actionbaractivity {private Button button;private TextView tv;private TextView textview;private ProgressBar    Progressbar;private static final String TAG = "Async_task";p rivate int x = 123;    private int y = 456;    Private MyTask Mtask;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main);        System.loadlibrary ("Twolib-second");     TV = (TextView) Findviewbyid (R.ID.TEXTVIEW2);   Button = (button) This.findviewbyid (R.id.button1);        TextView = (TextView) Findviewbyid (R.ID.TEXTVIEW3); This.button.setOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {mtask = new mytask (); mTa    Sk.execute ("Test");});        } public native int add (int x,int y);  @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the action Bar        If it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }//Async task Private class MytaSK extends Asynctask<string, Integer, string> {@Override protected void OnPreExecute () {//TODO Auto-gen    Erated method stub//Super.onpreexecute ();    LOG.I (TAG, "OnPreExecute () called");        Textview.settext ("Loading ...");                }//Processing time-consuming task @Override protected string Doinbackground (String ... arg0) {//TODO auto-generated method stub                try {int z = Add (x, y);                TV = (TextView) Findviewbyid (R.ID.TEXTVIEW2);                Tv.settext ("The sum dskdshd of" + x + "and" + y + "is" + Z);            return new String ("test");              } catch (Exception e) {log.e (TAG, E.getmessage ());      } return null; } @Override protected void Onprogressupdate (Integer ... values) {//TODO auto-generated method stub//Supe    R.onprogressupdate (values);    Progressbar.setprogress (Values[0]);    Textview.settext ("Loading ..." + "%"); } @Override protected VOID OnPostExecute (String result) {//TODO auto-generated method stub//Super.onpostexecute (result);    Textview.settag (result); }    }    }

Attention:

1, about the UI used in the code, the reader to drag themselves into the layout, this is not in detail

2, Android is currently more commonly used for the handle mechanism, due to the author's Android level is limited, the simplest asynchronous task implementation is chosen. Interested readers, implement other methods on their own

3, run: Click the leftmost button, return the following results, if the 0 surface program in the 3 URL request success, if the other fails to return, Curl returns the error code see above blog.


Using Libcurl third-party libraries for Android asynchronous tasks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.