0
我已經寫了一個本地類來從互聯網下載,我想從JavaScript調用該代碼。我可以在webview中調用JavaScript中的本地代碼,但我不知道如何在JavaScript中調用本地事件。在javascript中處理本地事件android
這是本機代碼:
public class DonwloadTask extends AsyncTask<URL,Void,Long> {
private OnTaskCompleted listener;
private String result;
public DonwloadTask(OnTaskCompleted listener){
this.listener=listener;
}
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
StringBuilder resultBuilder = new StringBuilder();
for (int i = 0; i < count; i++) {
try {
// Read all the text returned by the server
InputStreamReader reader = new InputStreamReader(urls[i].openStream());
BufferedReader in = new BufferedReader(reader);
String resultPiece;
while ((resultPiece = in.readLine()) != null) {
resultBuilder.append(resultPiece);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// if cancel() is called, leave the loop early
if (isCancelled()) {
break;
}
}
// save the result
this.result = resultBuilder.toString();
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
// update progress here
}
// called after doInBackground finishes
protected void onPostExecute(Long result) {
//Log.v("API", this.result);
// put result into a json object
try {
JSONObject jsonObject = new JSONObject(this.result);
// call callback
listener.onTaskCompleted(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
</code>
And this is interface for event
<code>
public interface OnTaskCompleted {
String onTaskCompleted(JSONObject result);
}
</code>
And this is class wrapped the DownloadTask
<code>
public class NativeApi implements OnTaskCompleted {
private DonwloadTask task;
public NativeApi(){
task= new DonwloadTask(this);
}
public void startDownload(String urlStr){
URL url= null;
try {
url = new URL(urlStr);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
@Override
public String onTaskCompleted(JSONObject result) {
return result.toString();
}
}
</code>
And javascript to call native code
<code>
function startDownload(url){
NativeApi.startDownload(url);
}
</code>
我如何訂閱onTaskCompleted在JavaScript?