我知道我必须调用onpause()
或ondestroy()
停止媒体播放器的方法我必须初始化媒体播放器,但在我的情况下,我调用 html 并使用 android 和 html 之间的接口作为 html 上的调用 android 方法。我尝试从接口中获取实例:
WebAppInterface wb= new WebAppInterface(mContext);
在界面上我初始化了媒体播放器:
public MediaPlayer mp = MediaPlayer.create(mContext,R.raw.sound);
在主要活动中,我尝试在 oncreate()
方法中初始化媒体播放器:
mediaplayer=wb.mp;
主要活动:
public class Ramadan extends Activity {
private MediaPlayer mediaplayer;
Context mContext;
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");
mediaplayer=wb.mp;
}
@Override
protected void onPause()
{
super.onPause();
if(mediaplayer.isPlaying())
mediaplayer.pause(); //stop the sound
}
@Override
protected void onResume()
{
super.onResume();
if(WebAppInterface.checked)
{
mediaplayer.start();
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(WebAppInterface.checked)
{
mediaplayer.stop();
}
}
界面:
Context mContext;
public MediaPlayer mp = MediaPlayer.create(mContext,R.raw.sound);
public static boolean checked = false;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
@JavascriptInterface
public void playsound(String value ) {
if (value.equals("on")) {
checked = true;
mp.setLooping(true);
mp.start();
}
else
{
checked = false;
mp.stop();
}
}
}
日志猫:
07-01 10:56:20.421: E/AndroidRuntime(636): java.lang.RuntimeException:
Unable to instantiate activity ComponentInfo{com.ramadan/com.ramadan.Ramadan}: java.lang.NullPointerException