我想在webview加载特殊网址时激活传感器,所以我在webview定义中使用了sensorManager.registerListener
:
@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()
无法正常工作。在这里获取上下文的标准方法是什么?
答案 0 :(得分:1)
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);
}
}
//根据您的要求使用此内容或上下文
答案 1 :(得分:1)
在MainActivity.java中添加以下代码
public class MainActivity extends AppCompatActivity {
public static MainActivity context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
}
public static MainActivity getInstance()
{
return context;
}
}
通过调用此方法来使用此上下文
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("compass")){
sensorManager.registerListener(MainActivity.getInstance(), compass, SensorManager.SENSOR_DELAY_NORMAL);
}
}