0
我知道我必須調用onpause()
或ondestroy()
方法來停止媒體播放器我必須初始化媒體播放器,但在我的情況下,我調用html並使用android和html之間的接口作爲在html上調用android方法。我嘗試從接口有實例爲:如何在Android Java中從接口類初始化媒體播放器?
WebAppInterface wb= new WebAppInterface(mContext);
,並在接口I初始化的媒體播放器:
public MediaPlayer mp = MediaPlayer.create(mContext,R.raw.sound);
,並在主要活動中我嘗試initalize媒體播放器在oncreate()
方法:
mediaplayer=wb.mp;
MainActivity:
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();
}
}
}
的logcat:
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
但我初始化它的OnCreate()作爲我增加媒體播放= wb.mp;爲什麼它沒有初始化 – egydeveloper
應用程序在啓動時停止 – egydeveloper
請發佈堆棧跟蹤崩潰 – Chandan