调用onPause后报警继续播放

时间:2017-01-09 18:23:47

标签: java android

这是一个定时器的代码,一旦达到0就播放声音(定时器工作正常)。问题是即使onPause()调用了MainActivity.java,声音也会持续存在。

我在onDestroy()中实施了SimpleIntentService.java来停止声音,但显然在调用finish()时,{@ 1}}从未调用过它。当应用程序暂停时,我怎么能让声音停止?

这是我的Activity

MainActivity.java

public class MainActivity extends Activity { private BroadcastReceiver broadcastReceiver; NumberPicker picker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); picker = (NumberPicker) findViewById(minutePicker); Log.i("TurnToTech", "Project Name - SimpleBackgroundService"); picker.setMinValue(0); picker.setMaxValue(20); broadcastReceiver = new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent intent) { String text = intent.getStringExtra(SimpleIntentService.PARAM_OUT_MSG); Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } }; } Intent msgIntent; public void startTimer(View view) { setContentView(R.layout.activity_main); msgIntent = new Intent(this, SimpleIntentService.class); msgIntent.putExtra(SimpleIntentService.PARAM_IN_MSG, "Alarm: "); msgIntent.putExtra("time", picker.getValue()); startService(msgIntent); } public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(SimpleIntentService.ACTION_RESP); filter.addCategory(Intent.CATEGORY_DEFAULT); registerReceiver(broadcastReceiver,filter); } public void onPause() { finish(); unregisterReceiver(broadcastReceiver); super.onPause(); } }

SimpleIntentService.java

1 个答案:

答案 0 :(得分:1)

在您的IntentService中,您并未在onDestroy功能中停止相同的闹钟。因为每次你获得它的新实例。

所以我想建议保留Ringtone的公共静态变量,以便可以从任何地方访问它。在MainActivity中声明它们。

public static Ringtone r; 
public static Uri alert;

onCreate的{​​{1}}函数中初始化它们。

MainActivity

现在@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // ... Other statements // Initialize ringtone here initializeRingtone(); } private void initializeRingtone() { alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); r = RingtoneManager.getRingtone(getApplicationContext(), alert); } 的{​​{1}}功能应该如下所示

onPause()

如果您想在从后台恢复应用程序后播放声音然后计时器用完,您可以考虑在MainActivity public void onPause() { unregisterReceiver(broadcastReceiver); r.stop(); super.onPause(); } 函数中执行此类操作>

onResume

MainActivity中的public void onResume() { super.onResume(); registerReceiver(broadcastReceiver); initializeRingtone(); // Initialize it again. } 函数可能如下所示。

playSound()

希望有所帮助!