首页 > 解决方案 > 如何在 WebView 定义中获取上下文?

问题描述

我想在 webview 加载特殊 url 时激活传感器,所以我sensorManager.registerListener在 webview 定义中使用:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url.contains("compass")){
        sensorManager.registerListener(view.getContext().getApplicationContext(), compass, SensorManager.SENSOR_DELAY_NORMAL);
    }
}

不幸view.getContext().getApplicationContext()的是不工作。在这里获取上下文的标准方法是什么?

标签: androidandroid-webviewandroid-context

解决方案


private Context context;

public Yourclassname(Context context) {//constructor
this.context = context;

在您的代码中使用该上下文

SensorManager mSensorMgr = (SensorManager) 
context.getSystemService(Context.SENSOR_SERVICE);

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("compass")){

sensorManager.registerListener(context, 
compass, SensorManager.SENSOR_DELAY_NORMAL);
 }
}

//根据你的类使用这个或上下文


推荐阅读