我增添了新的界面,我可以打電話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
的可能重複[如何從Android中Java接口類初始化的媒體播放器?(http://stackoverflow.com/questions/17400864/how-to-initialize-media-player-from-interface-class-in -android-java) – Jerad