Use the libcurl third-party library to implement Android asynchronous tasks, libcurlandroid

Source: Internet
Author: User

Use the libcurl third-party library to implement Android asynchronous tasks, libcurlandroid

This article undertakes from the previous blog will Cocos2d-x libcurl separately packaged to Android

On this basis, further use is made:

1) added the libcurl Asynchronous Method.

2) Implement Android asynchronous tasks

The following code is directly used:

1] The first. c: first. h of jni is unchanged. Add the following code to first. c. Remember that the C variable must declare the beginning of the method function.

/** Copyright (C) 2009 The Android Open Source Project ** Licensed under the Apache License, Version 2.0 (the "License "); * you may not use this file before t in compliance with the License. * You may obtain a copy of the License at ** http://www.apache.org/licenses/LICENSE-2.0 ** Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on An "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.co M "," http://www.cocoachina.com/bbs/read.php? Tid = 228963 "," http://www.cnblogs.com/zhaoyl/p/4001151.html "}; // Asynchronous Method for retrieving returned 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;} // Add a URL request, asynchronous is essentially a combination of multiple synchronous requests CURL * curl_easy_handler (const char * sUrl, const char * sProxy, char * sRsp, unsi Gned int uiTimeout) {CURL * curl = curl_easy_init (); curl_easy_setopt (curl, CURLOPT_URL, sUrl); curl_easy_setopt (curl, timeout, 1); if (uiTimeout> 0) {curl_easy_setopt (curl, CURLOPT_TIMEOUT_MS, uiTimeout);} if (sProxy [0]! = '\ 0') {curl_easy_setopt (curl, CURLOPT_PROXY, sProxy);} curl_easy_setopt (curl, scheme, curl_writer); curl_easy_setopt (curl, CURLOPT_WRITEDATA, & sRsp ); // log ("curl_write = % lu", sizeof (sRsp); return curl;} // select method, select the currently readable 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_t t; int max_fd =-1; int ret_code; FD_ZERO (& fd_read ); FD_ZERO (& fd_write); FD_ZERO (& fd_except); timeout_ TV. TV _sec = 60; rows = 0; curl_multi_fdset (curl_m, & fd_read, & fd_write, & fd_except, & 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, & timeout_ TV); ret_code = select (max_fd + 1, & fd_read, & fd_write, & fd_except, & timeout_ TV ); // log ("ret_code = % d", ret_code); switch (ret_code) {case-1: ret =-1; break; case 0: default: ret = 0; break;} return ret;} // Asynchronous 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 up = % 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; // pass the result status to the result array, which 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 ;} // 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] jni second. c

# 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" loads (JNIEnv * env, jobject this, jint x, jint y) {/* // libcurl Synchronization 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, scheme, 1); curl_easy_setopt (curl, scheme, 20); curl_easy_setopt (curl, CURLOPT_TIMEOUT, 20); res = curl_easy_perform (curl ); curl_easy_cleanup (curl); * // case of libcurl Asynchronous Method CURLcode result [3]; int sum; gettimeofday (& begin_ TV, NULL); curl_multi_demo (3, result ); gettimeofday (& end_ TV, NULL); long eclapsed = (end_ TV. TV _sec-begin_ TV. TV _sec) * 1000 + (end_ TV. TV _usec-timeout)/1000; // log ("eclaptime: % 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"; private 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 (); mTask.exe cute ("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 will // 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);} // asynchronous task private class MyTask extends AsyncTask <String, Integer, String >{@ Override protected void onPreExecute () {// TODO Auto-generated method stub // super. onPreExecute (); Log. I (TAG, "onPreExecute () called"); textView. setText ("Loading... ");} // process 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 // super. 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 );}}}

Note:

1. Drag the UI used in the code to layout by yourself. This is not detailed here.

2. handle mechanism is commonly used in Android. Due to the limited Android level, the author selects the simplest asynchronous task implementation. If you are interested, implement other methods on your own.

3. Run: Click the leftmost button and return the following results. If the three URLs in the 0 surface program are successfully requested, otherwise, the request fails. For the error code returned by curl, see the blog above.


Related Article

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.