CCDownloader-android.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /****************************************************************************
  2. Copyright (c) 2015-2016 Chukong Technologies Inc.
  3. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. ****************************************************************************/
  21. #include "network/CCDownloader-android.h"
  22. #include "network/CCDownloader.h"
  23. #include "platform/android/jni/JniHelper.h"
  24. #include <mutex>
  25. #define JCLS_DOWNLOADER "org/cocos2dx/lib/Cocos2dxDownloader"
  26. #define JCLS_TASK "com/loopj/android/http/RequestHandle"
  27. #define JARG_STR "Ljava/lang/String;"
  28. #define JARG_DOWNLOADER "L" JCLS_DOWNLOADER ";"
  29. #define JARG_TASK "L" JCLS_TASK ";"
  30. using namespace std;
  31. static bool _registerNativeMethods(JNIEnv* env);
  32. unordered_map<int, cocos2d::network::DownloaderAndroid*> sDownloaderMap;
  33. std::mutex sDownloaderMutex;
  34. static void _insertDownloaderAndroid(int id, cocos2d::network::DownloaderAndroid* downloaderPtr)
  35. {
  36. std::lock_guard<std::mutex> guard(sDownloaderMutex);
  37. sDownloaderMap.insert(make_pair(id, downloaderPtr));
  38. }
  39. static void _eraseDownloaderAndroid(int id)
  40. {
  41. std::lock_guard<std::mutex> guard(sDownloaderMutex);
  42. sDownloaderMap.erase(id);
  43. }
  44. /**
  45. * If not found, return nullptr, otherwise return the Downloader
  46. */
  47. static cocos2d::network::DownloaderAndroid* _findDownloaderAndroid(int id)
  48. {
  49. std::lock_guard<std::mutex> guard(sDownloaderMutex);
  50. auto iter = sDownloaderMap.find(id);
  51. if (sDownloaderMap.end() == iter) {
  52. return nullptr;
  53. } else {
  54. return iter->second;
  55. }
  56. }
  57. namespace cocos2d { namespace network {
  58. static int sTaskCounter;
  59. static int sDownloaderCounter;
  60. static bool _registered = false;
  61. struct DownloadTaskAndroid : public IDownloadTask
  62. {
  63. DownloadTaskAndroid()
  64. :id(++sTaskCounter)
  65. {
  66. DLLOG("Construct DownloadTaskAndroid: %p", this);
  67. }
  68. virtual ~DownloadTaskAndroid()
  69. {
  70. DLLOG("Destruct DownloadTaskAndroid: %p", this);
  71. }
  72. int id;
  73. shared_ptr<const DownloadTask> task; // reference to DownloadTask, when task finish, release
  74. };
  75. DownloaderAndroid::DownloaderAndroid(const DownloaderHints& hints)
  76. : _id(++sDownloaderCounter)
  77. , _impl(nullptr)
  78. {
  79. DLLOG("Construct DownloaderAndroid: %p", this);
  80. JniMethodInfo methodInfo;
  81. if (JniHelper::getStaticMethodInfo(methodInfo,
  82. JCLS_DOWNLOADER,
  83. "createDownloader",
  84. "(II" JARG_STR "I)" JARG_DOWNLOADER))
  85. {
  86. jobject jStr = methodInfo.env->NewStringUTF(hints.tempFileNameSuffix.c_str());
  87. jobject jObj = methodInfo.env->CallStaticObjectMethod(
  88. methodInfo.classID,
  89. methodInfo.methodID,
  90. _id,
  91. hints.timeoutInSeconds,
  92. jStr,
  93. hints.countOfMaxProcessingTasks
  94. );
  95. _impl = methodInfo.env->NewGlobalRef(jObj);
  96. DLLOG("android downloader: jObj: %p, _impl: %p", jObj, _impl);
  97. //It's not thread-safe here, use thread-safe method instead
  98. //sDownloaderMap.insert(make_pair(_id, this));
  99. _insertDownloaderAndroid(_id, this);
  100. methodInfo.env->DeleteLocalRef(jStr);
  101. methodInfo.env->DeleteLocalRef(jObj);
  102. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  103. }
  104. }
  105. DownloaderAndroid::~DownloaderAndroid()
  106. {
  107. if(_impl != nullptr)
  108. {
  109. JniMethodInfo methodInfo;
  110. if (JniHelper::getStaticMethodInfo(methodInfo,
  111. JCLS_DOWNLOADER,
  112. "cancelAllRequests",
  113. "(" JARG_DOWNLOADER ")V"))
  114. {
  115. methodInfo.env->CallStaticVoidMethod(
  116. methodInfo.classID,
  117. methodInfo.methodID,
  118. _impl
  119. );
  120. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  121. }
  122. //It's not thread-safe here, use thread-safe method instead
  123. //sDownloaderMap.erase(_id);
  124. _eraseDownloaderAndroid(_id);
  125. JniHelper::getEnv()->DeleteGlobalRef(_impl);
  126. }
  127. DLLOG("Destruct DownloaderAndroid: %p", this);
  128. }
  129. IDownloadTask *DownloaderAndroid::createCoTask(std::shared_ptr<const DownloadTask>& task)
  130. {
  131. DownloadTaskAndroid *coTask = new DownloadTaskAndroid;
  132. coTask->task = task;
  133. JniMethodInfo methodInfo;
  134. if (JniHelper::getStaticMethodInfo(methodInfo,
  135. JCLS_DOWNLOADER,
  136. "createTask",
  137. "(" JARG_DOWNLOADER "I" JARG_STR JARG_STR")V"))
  138. {
  139. jstring jstrURL = methodInfo.env->NewStringUTF(task->requestURL.c_str());
  140. jstring jstrPath= methodInfo.env->NewStringUTF(task->storagePath.c_str());
  141. methodInfo.env->CallStaticVoidMethod(methodInfo.classID, methodInfo.methodID, _impl, coTask->id, jstrURL, jstrPath);
  142. methodInfo.env->DeleteLocalRef(jstrURL);
  143. methodInfo.env->DeleteLocalRef(jstrPath);
  144. methodInfo.env->DeleteLocalRef(methodInfo.classID);
  145. }
  146. DLLOG("DownloaderAndroid::createCoTask id: %d", coTask->id);
  147. _taskMap.insert(make_pair(coTask->id, coTask));
  148. return coTask;
  149. }
  150. void DownloaderAndroid::_onProcess(int taskId, int64_t dl, int64_t dlNow, int64_t dlTotal)
  151. {
  152. DLLOG("DownloaderAndroid::onProgress(taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", taskId, dl, dlNow, dlTotal);
  153. auto iter = _taskMap.find(taskId);
  154. if (_taskMap.end() == iter)
  155. {
  156. DLLOG("DownloaderAndroid::onProgress can't find task with id: %d", taskId);
  157. return;
  158. }
  159. DownloadTaskAndroid *coTask = iter->second;
  160. function<int64_t(void*, int64_t)> transferDataToBuffer;
  161. onTaskProgress(*coTask->task, dl, dlNow, dlTotal, transferDataToBuffer);
  162. }
  163. void DownloaderAndroid::_onFinish(int taskId, int errCode, const char *errStr, vector<unsigned char>& data)
  164. {
  165. DLLOG("DownloaderAndroid::_onFinish(taskId: %d, errCode: %d, errStr: %s)", taskId, errCode, (errStr)?errStr:"null");
  166. auto iter = _taskMap.find(taskId);
  167. if (_taskMap.end() == iter)
  168. {
  169. DLLOG("DownloaderAndroid::_onFinish can't find task with id: %d", taskId);
  170. return;
  171. }
  172. DownloadTaskAndroid *coTask = iter->second;
  173. string str = (errStr ? errStr : "");
  174. _taskMap.erase(iter);
  175. onTaskFinish(*coTask->task,
  176. errStr ? DownloadTask::ERROR_IMPL_INTERNAL : DownloadTask::ERROR_NO_ERROR,
  177. errCode,
  178. str,
  179. data
  180. );
  181. coTask->task.reset();
  182. }
  183. void _preloadJavaDownloaderClass()
  184. {
  185. if(!_registered)
  186. {
  187. _registered = _registerNativeMethods(JniHelper::getEnv());
  188. }
  189. }
  190. }
  191. } // namespace cocos2d::network
  192. static void _nativeOnProgress(JNIEnv *env, jclass clazz, jint id, jint taskId, jlong dl, jlong dlnow, jlong dltotal)
  193. {
  194. DLLOG("_nativeOnProgress(id: %d, taskId: %d, dl: %lld, dlnow: %lld, dltotal: %lld)", id, taskId, dl, dlnow, dltotal);
  195. //It's not thread-safe here, use thread-safe method instead
  196. cocos2d::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id);
  197. if (nullptr == downloader)
  198. {
  199. DLLOG("_nativeOnProgress can't find downloader by key: %p for task: %d", clazz, id);
  200. return;
  201. }
  202. downloader->_onProcess((int)taskId, (int64_t)dl, (int64_t)dlnow, (int64_t)dltotal);
  203. }
  204. static void _nativeOnFinish(JNIEnv *env, jclass clazz, jint id, jint taskId, jint errCode, jstring errStr, jbyteArray data)
  205. {
  206. DLLOG("_nativeOnFinish(id: %d, taskId: %d)", id, taskId);
  207. //It's not thread-safe here, use thread-safe method instead
  208. cocos2d::network::DownloaderAndroid *downloader = _findDownloaderAndroid(id);
  209. if (nullptr == downloader)
  210. {
  211. DLLOG("_nativeOnFinish can't find downloader id: %d for task: %d", id, taskId);
  212. return;
  213. }
  214. vector<unsigned char> buf;
  215. if (errStr)
  216. {
  217. // failure
  218. const char *nativeErrStr = env->GetStringUTFChars(errStr, JNI_FALSE);
  219. downloader->_onFinish((int)taskId, (int)errCode, nativeErrStr, buf);
  220. env->ReleaseStringUTFChars(errStr, nativeErrStr);
  221. return;
  222. }
  223. // success
  224. if (data)
  225. {
  226. int len = env->GetArrayLength(data);
  227. if (len)
  228. {
  229. buf.reserve(len);
  230. buf.resize(len);
  231. env->GetByteArrayRegion(data, 0, len, reinterpret_cast<jbyte*>(buf.data()));
  232. }
  233. }
  234. downloader->_onFinish((int)taskId, (int)errCode, nullptr, buf);
  235. }
  236. static JNINativeMethod sMethodTable[] = {
  237. { "nativeOnProgress", "(IIJJJ)V", (void*)_nativeOnProgress },
  238. { "nativeOnFinish", "(III" JARG_STR "[B)V", (void*)_nativeOnFinish },
  239. };
  240. static bool _registerNativeMethods(JNIEnv* env)
  241. {
  242. jclass clazz = env->FindClass(JCLS_DOWNLOADER);
  243. if (clazz == NULL)
  244. {
  245. DLLOG("_registerNativeMethods: can't find java class:%s", JARG_DOWNLOADER);
  246. return false;
  247. }
  248. if (JNI_OK != env->RegisterNatives(clazz, sMethodTable, sizeof(sMethodTable) / sizeof(sMethodTable[0])))
  249. {
  250. DLLOG("_registerNativeMethods: failed");
  251. if (env->ExceptionCheck())
  252. {
  253. env->ExceptionClear();
  254. }
  255. return false;
  256. }
  257. return true;
  258. }