【问题标题】:Android JavascriptInterface use context to call method in activity (OOP)Android JavascriptInterface 使用上下文调用活动中的方法(OOP)
【发布时间】:2017-06-24 17:01:28
【问题描述】:

OOP 中,我可以使用对象来调用它的方法。所以我想在android中使用相同的概念来做到这一点。但是,它不起作用。我用context调用了函数updateLvl(int),却说方法无法解析。我想知道如何使用context调用方法updateLvl

public class MainActivity extends Activity {

private WebView webview;
SharedPreferences sharedPref;
SharedPreferences.Editor editor;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);


    sharedPref = this.getPreferences(0);
    editor = sharedPref.edit();

    webview = new WebView(this);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.addJavascriptInterface(new WebViewJavaScriptInterface2(this), "app");


public void updateLvl(int newLvl){
    sharedPref = this.getPreferences(0);
    editor = sharedPref.edit();
    int be4Level = sharedPref.getInt("currLevel", 1);
    if (newLvl >= be4Level){
        editor.putInt("currLevel", newLvl);
        editor.commit();
    }
  }


}

class WebViewJavaScriptInterface2{

private Context context;
/*
 * Need a reference to the context in order to sent a post message
 */
public WebViewJavaScriptInterface2(Context context){
    this.context = context;
}

@JavascriptInterface
public void openLvl(int lvl){
    context.updateLvl(lvl);
}

}

【问题讨论】:

    标签: android oop


    【解决方案1】:

    您需要将context 转换为MainActivity,因为您的MainActivity 类具有updateLvl 方法而不是Context 类,因此编译器会在应用静态绑定时向您显示错误

    @JavascriptInterface
    public void openLvl(int lvl){
        if(context instanceof MainActivity) // add safety check if required
            ((MainActivity)context).updateLvl(lvl);
    }
    

    【讨论】:

      【解决方案2】:

      Context 不是你的WebViewJavaScriptInterface2 的实例,而是android 系统的一个类(以及Activity)。

      一种方法是按照 Pavneet 的建议将上下文转换为活动。但这有一个缺陷,你不能绝对确定你的 WebViewJavaScriptInterface2 是从正确的活动中实例化的。如果你将它投射到那个活动,你也可以只从一个活动中使用它。

      更简洁的方法是定义一个回调接口,在您的活动(或多个活动)中实现该接口并将该回调接口传递给WebViewJavaScriptInterface2

      【讨论】:

        【解决方案3】:

        这可能对某人有所帮助。

        new Handler(Looper.getMainLooper())
          .post(new Runnable(){
            @override
            public void run(){
              updateLvl(lvl);
            }
          });
        

        【讨论】:

          猜你喜欢
          • 2016-06-20
          • 2016-09-14
          • 2012-03-28
          • 1970-01-01
          • 1970-01-01
          • 2012-06-15
          • 2016-01-08
          • 1970-01-01
          相关资源
          最近更新 更多