我添加了新接口,因为我可以在html中调用 android 方法。主要活动将html文件调用到我的webview和接口类以执行播放声音的播放方法。一切正常,但是当我添加代码以在关闭应用程序时停止声音或在按下返回键或主页键时关闭声音。但是当按下返回或主页键时也会出现错误“应用程序停止...... ”在旋转时发生。
public class x extends Activity {
private MediaPlayer mp;
private String TAG;
Context mContext;
private IntentListener listener = new IntentListener();
WebAppInterface wb= new WebAppInterface(mContext);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
//Call HTML Files
WebView myWebView = (WebView) findViewById(R.id.web_engine);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
// Intiate interface
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
}
@Override
protected void onPause()
{
super.onPause();
if(mp.isPlaying())
mp.pause(); //stop the sound
}
@Override
protected void onResume()
{
super.onResume();
if(WebAppInterface.checked)
{
mp.start();
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(WebAppInterface.checked)
{
mp.stop();
}
}
}
public class WebAppInterface {
Context mContext;
private MediaPlayer mp;
public static boolean checked = false;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void playsound(String value ) {
if (value.equals("on")) {
checked = true;
mp= MediaPlayer.create(mContext,R.raw.sound);
mp.setLooping(true);
mp.start();
}
else
{
checked = false;
mp.stop();
}
}
}
<activity
android:name="com.ramadan.Ramadan"
android:label="@string/app_name">
07-01 01:06:29.628: E/AndroidRuntime(631): java.lang.RuntimeException: Unable to pause activity {com.ramadan/com.ramadan.Ramadan}: java.lang.NullPointerException