2017-01-09 3 views
1

Вот код для таймера, который воспроизводит звук после достижения 0 (таймер работает отлично). Проблема в том, что звук сохраняется даже через onPause() в MainActivity.java.Тревога продолжает играть после onPause под названием

Я реализовал onDestroy() в SimpleIntentService.java, чтобы остановить звук, но, видимо, никогда не называют даже finish() в вызывающем 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

public class SimpleIntentService extends IntentService { 
    public static final String PARAM_IN_MSG = "in_msg"; 
    public static final String PARAM_OUT_MSG = "out_msg"; 
    int time; 

    public static final String ACTION_RESP = "org.turntotech.intent.action.MESSAGE_PROCESSED"; 

    public SimpleIntentService() { 
     super("SimpleIntentService"); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     System.out.println("SimpleIntentService Called"); 
     String msg = intent.getStringExtra(PARAM_IN_MSG); 
     int time = intent.getIntExtra("time", 0); 

     // Timer implementation 
     if (time == 0){ 
      playSound(); 
     } 

     while(time > 0){ 

      SystemClock.sleep(5000); // 5 seconds 
      time -= 5; 
      String resultTxt = msg + time + " seconds remaining"; 
      Intent broadcastIntent = new Intent(); 

      broadcastIntent.setAction(ACTION_RESP); 
      broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT); 
      broadcastIntent.putExtra(PARAM_OUT_MSG, resultTxt); 
      broadcastIntent.putExtra("time", time); 

      sendBroadcast(broadcastIntent); 
      if (time == 0) { 
       playSound(); 
      } 
     } 
    } 

    Uri alert; 

    public void playSound(){ 
     alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); 
     Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), alert); 
     r.play(); 
    } 

    public void onDestroy() { 
     Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), alert); 
     r.stop(); 

     super.onDestroy(); 
    } 
} 

ответ

1

В вашей IntentService вы на самом деле не остановить ту же тревогу в вашей onDestroy функции. Потому что каждый раз, когда вы получаете новый экземпляр.

Поэтому я хотел бы предложить сохранить общедоступную статическую переменную Ringtone, чтобы к ней можно было получить доступ из любой точки мира. Объявите их в своем MainActivity.

public static Ringtone r; 
public static Uri alert; 

Инициализировать их в onCreate функции вашего 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); 
} 

Теперь 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() Функция в IntentService может выглядеть так.

public void playSound(){ 
    // Initialize the alert and ringtone again. 
    MainActivity.alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); 
    MainActivity.r = RingtoneManager.getRingtone(getApplicationContext(), alert); 

    MainActivity.r.play(); 
} 

public void onDestroy() { 
    MainActivity.r.stop(); 
    super.onDestroy(); 
} 

Надеюсь, что это поможет!

+0

Большое спасибо, но, к сожалению, звук не начинает воспроизводиться при реализации этого способа. Просто мертвая тишина после истечения таймера, любая идея, почему? –

+0

Какой здесь сценарий? Вы взяли приложение в фоновом режиме, и таймер прекратил играть правильно? Опять же, вы возобновили приложение, и вы ожидаете, что звук должен воспроизводиться после истечения таймера? –

+0

См. Обновленный ответ. Это может помочь. –

Смежные вопросы