【发布时间】:2013-06-26 21:25:05
【问题描述】:
我有新代码可以在单击移动设备中的静音按钮或单击后退按钮“从应用程序中退出”时停止播放声音。我在下面做了我的代码,但声音仍在播放,虽然我没有任何错误。
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 类
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();}
}
意图监听类
public class IntentListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//here code do be executed on when intent comes
}
}
清单
<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>
【问题讨论】:
-
对您的问题进行更多解释会很好。目前你只是向我们扔代码并说它没有停止......它应该在何时何地停止,何时不停止?
-
它必须在按下锁定移动按钮时停止,并且当我从移动设备按下返回按钮“out”时也会静音
-
我不明白:您想在应用程序外部按下后退按钮时停止播放 - 应用程序在后台播放 - 或当您“关闭”应用程序时?
-
我 不 明白: 你 想要 to stop playing when you push 返回 按钮 外部 应用程序 -with app playing in background-? 抱歉我编辑了:这就是你想要的,不是吗?我认为你不能,你应该发出通知以返回应用程序并关闭它。
标签: android eclipse android-mediaplayer