I have new code to stop play sound when click on mute button in mobile or click back button "out from app" . I did my code below but the sound still playing although I haven't any errors.
public class x extends Activity {
private MediaPlayer mp;
private String TAG;
Context mContext;
private IntentListener listener = new IntentListener();
WebAppInterface wb= new WebAppInterface(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ramadan);
//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 onStart() {
super.onStart();
}
@Override
protected void onResume() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(listener, intentFilter);
super.onResume();
}
@Override
protected void onStop() {
if (wb != null) {
wb.stop();
}
super.onStop();
}
@Override
protected void onPause() {
super.onPause();
wb.pause();
unregisterReceiver(listener);
}
@Override
public void onDestroy(){
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
if (intentFilter !=null){
Log.v("SERVICE","Service killed");
wb.stop();
}
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
mp= MediaPlayer.create(Ramadan.this,R.raw.sound);
if(mp.isPlaying())
{
mp.stop();
return true;
}
}
else return false;
}
}
WebAppInterface class
public class WebAppInterface {
Context mContext;
private MediaPlayer mp;
WebAppInterface(Context c) {
mContext = c;
}
public void pause( ) {
mp= MediaPlayer.create(mContext,R.raw.sound);
if(mp!=null)
{
mp.pause();}
}
public void stop( ) {
mp= MediaPlayer.create(mContext,R.raw.sound);
if(mp!=null)
{
mp.stop();
mp.release();
}
}
@JavascriptInterface
public void playsound(String value ) {
if (value.equals("on")) {
mp= MediaPlayer.create(mContext,R.raw.sound);
mp.start();
}
else
{ mp.stop();}
}
intent listener class
public class IntentListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//here code do be executed on when intent comes
}
}
manifest
<activity
android:name="com.x.y"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.ACTION_SCREEN_OFF"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>