来自JavascriptInterface的android startActivity [英] android startActivity from JavascriptInterface
问题描述
一个简单的一般性问题.
Simple general question.
Webview已连接到我的JavascriptInterface类,并且肯定可以正常运行.但是,由于JavascriptInterface不会扩展Activity,因此我似乎无法使用startActivity(intent);来进行新的活动.
Webview is hooked up to my JavascriptInterface class and it is most certainly functional. However, because JavascriptInterface does not extend Activity, I cannot seem to Intent to a new activity using startActivity(intent);
我应该扩展活动吗?是否有另一种意图进行另一项活动的方法? (在我的特例中,我试图使用YouTube应用)
Should I extend Activity? Is there another method to intent to another activity? (in my very special case, im trying to intent to the YouTube app)
package com.privateized.moreprivate;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.widget.Toast;
public class JavaScriptInterface {
Context mContext;
/** Instantiate the interface and set the context */
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
///// vvvvv This no Worky vvvvv Just crashes ////////
public void YouTube(String id) {
Log.d("JS", "Launching YouTube:" + id);
Activity activity = new Activity();
String videoId = id;
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:"+videoId));
i.putExtra("VIDEO_ID", videoId);
Log.d("JS", "Starting Activity");
activity.startActivity(i);
}
}
推荐答案
只需使用mContext.startActivity(i)
;
无需创建活动,也无需扩展活动,只需引用已存储的上下文即可.
No need to ever create Activity and no need to extend Activity, you just need a reference to Context which you already have stored.
这篇关于来自JavascriptInterface的android startActivity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!