android - 如何在 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()
的是不工作。在这里获取上下文的标准方法是什么?
解决方案
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);
}
}
//根据你的类使用这个或上下文
推荐阅读
- c - 正确分配内存和释放?
- javascript - 从两个数组中获取相同对象的数组
- c - 套接字之间“通信”的最佳方式
- r - Kable 强制我的表格高于我在 R 中的文本,我该如何解决这个问题?
- android - Kotlin (Android) - 如何从一个线程发布自定义事件并在主线程中监听该事件?
- python - Python 正则表达式查找从上一个匹配项开始的匹配项
- python - Python如何每30秒运行一次脚本,然后发送不和谐的消息
- android - setState() 不渲染屏幕上的变量变化
- r - 使用 rvest 在抓取的元素之间创建一个空间
- html - CSS过渡未应用于菜单中的下拉项