1

Я сделал будильник в студии Android. Я могу запустить приложение, Все работает отлично, за исключением воспроизведения звукового кольца. На самом деле звук не воспроизводится, когда приходит время будильника. Я не знаю, что случилось с моим кодом. Пожалуйста, помогите мне найти ошибку.Почему будильник не воспроизводит сигнал тревоги (звук)?

MainActivity:

package com.mycompany.alarmclock; 
//I haven't shown the imported stuff here. they are in my file. 
import android.support.v7.app.ActionBarActivity; 


public class MainActivity extends Activity { 

    AlarmManager alarmManager; 
    private PendingIntent pendingIntent;//an action to be performed by other/foreign application 
    private TimePicker alarmTimePicker;//In where the user set the time 
    private static MainActivity inst; 
    private TextView alarmTextView;//the area where alarm message/notification will be displayed 


    public static MainActivity instance() { 
     return inst; 
    } 

    public void onStart() { 
     super.onStart(); 
     inst = this; 
    } 

    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     alarmTimePicker = (TimePicker) findViewById(R.id.alarmTimePicker); 
     alarmTextView = (TextView) findViewById(R.id.alarmText); 
     ToggleButton alarmToggle = (ToggleButton) findViewById(R.id.alarmToggle); 
     alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
    } 


    public void onToggleClicked(View view) { 
     if (((ToggleButton) view).isChecked()) {//if toggle button is "ON" do the alarming function 
      Log.d("MainActivity", "Alarm On"); 
      Calendar calendar = Calendar.getInstance(); 
      calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour()); 
      calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute()); 
      Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class); 
      pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0); 
      alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); 

     } else { 
      alarmManager.cancel(pendingIntent); 
      setAlarmText(""); 
      Log.d("MyActivity", "Alarm Off"); 
     } 

    } 

    public void setAlarmText(String alarmText) { 
     alarmTextView.setText(alarmText); 

    } 



} 

AlarmReceiver:

package com.mycompany.alarmclock; 
//I haven't shown the imported stuff here. they are in my file. 
import android.support.v4.content.WakefulBroadcastReceiver; 

public class AlarmReceiver extends WakefulBroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     MainActivity inst=MainActivity.instance(); 
     inst.setAlarmText("Get Up! Get up!"); 
     Uri alarmUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); 

     if (alarmUri == null) { 
      alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 
     } 
     Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri); 
     ringtone.play(); 

     //this will send a notification message 
     ComponentName comp = new ComponentName(context.getPackageName(), 
       AlarmService.class.getName()); 
     startWakefulService(context, (intent.setComponent(comp))); 
     setResultCode(Activity.RESULT_OK); 
    } 
} 

AlarmService:

package com.mycompany.alarmclock; 
     //I haven't shown the imported stuff here. they are in my file. 
     import android.support.v4.app.NotificationCompat; 


     public class AlarmService extends IntentService { 

     private NotificationManager alarmnotificationManager; 

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

      @Override 
      protected void onHandleIntent(Intent intent) { 
       sendNotification("Get up! Get up!"); 

      } 
      private void sendNotification(String msg){ 

       Log.d("AlarmService","Sending notification...:"+msg); 
       alarmnotificationManager=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); 

       PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
         new Intent(this, MainActivity.class), 0); 

       NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
         this).setContentTitle("Alarm").setSmallIcon(R.drawable.ic_launcher) 
         .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) 
         .setContentText(msg); 


       alamNotificationBuilder.setContentIntent(contentIntent); 
       alarmnotificationManager.notify(1, alamNotificationBuilder.build()); 
       Log.d("AlarmService", "Notification sent."); 

      } 

     } 
+0

Где вы застряли? (Не говорите все это) –

+0

Я обновил свой пост с более подробным объяснением. код/​​приложение работает нормально. после того, как я установил время будильника, звук не воспроизводится. никаких предупреждений о тревоге - это единственная проблема. – Riyana

+0

ОК, так что будильник не работает вообще, верно? –

ответ

0

может быть, ваш медиа Том является низким или приглушенные

попробовать MediaPlayer, он имеет много вариантов

MediaPlayer mediaPlayer = new MediaPlayer(); 
mediaPlayer.setDataSource(context, ringtone); 
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM); 
mediaPlayer.setLooping(true); 
mediaPlayer.prepare(); 
mediaPlayer.start(); 
+0

Амир, мне нужно использовать его в качестве альтернативы ringtone.play()? В этом контексте вы немного более конкретны. – Riyana

+1

да это альтернатива. в любом случае RingtoneManager должен работать нормально. вы уверены, что все работает нормально? проверьте метод onReceiver() в AlarmReceiver. поместите там журнал или тост, чтобы убедиться. – Amir

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