2010-02-22 2 views
1

У меня есть класс, который устанавливает будильник, но мне нужно установить еще 10 таких аварийных сигналов. Вместо дублирования классов, есть ли способ, который я могу просто создать новый экземпляр класса и установить время будильника?Класс тревоги Android

Вот мой код.

import java.util.Calendar; 

import java.lang.String; 

import android.app.Activity; 
import android.app.AlarmManager; 
import android.app.ListActivity; 
import android.app.PendingIntent; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 

import android.content.Intent; 
import android.widget.Button; 
import android.widget.Toast; 


public class Alarm extends Activity { 
    /* for logging - see my tutorial on debuggin Android apps for more detail */ 
    private static final String TAG = "SomeApp "; 
    protected Toast mToast; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 


    setAlarm(); 
    } 





    public void setAlarm() { 


     try { 

     Calendar cal = Calendar.getInstance(); 

     cal.add(Calendar.DAY_OF_YEAR, 0); 
     cal.set(Calendar.HOUR_OF_DAY, 9); 
     cal.set(Calendar.MINUTE, 01); 
     cal.set(Calendar.SECOND, 0); 


     Intent intent  = new Intent(Alarm.this, Alarm1.class); 
     PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0); 
     PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0); 

     AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); 
     am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); // to be alerted 30 seconds from now 
     am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sende2); // to be alerted 15 seconds from now 

     /* To show how alarms are cancelled we will create a new  Intent and a new PendingIntent with the 
     * same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567. 
      * Note: The intent and PendingIntent have to be the same as the ones used to create the alarms. 
      */ 
     Intent intent1  = new Intent(Alarm.this, Alarm1.class); 
     PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0); 
     AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE); 
     am1.cancel(sender1); 


     } catch (Exception e) { 
      Log.e(TAG, "ERROR IN CODE:"+e.toString()); 
     } 
    } 

}; 





    b1.setOnClickListener(new View.OnClickListener() { 
        public void onClick(View v) { 


        // Intent i = new Intent(getContext(),Alarm.class); 



//Code below is from another class which is where im calling the alarm application 



         // ctx.startActivity (i);// start the Alarm class activity (class)public void onClick(View v) { 

         Alarm a = new Alarm(); 

         a.setAlarm(); 


         b1.setText(prod); 


        } 
       }); 

Приведенный выше код из другого класса и на кнопку мыши пользователь может установить напоминание (днище вызывает класс тревоги, только чтобы заставить его работать использует намерение. Я просто пытался позвонить метод setAlarm, но это не сработало Возможно, я мог бы создать новый экземпляр календаря и установить время в обработчике кнопок. Тогда мне пришлось бы передать этот экземпляр в класс тревоги. Знаете ли вы, возможно ли это ?

ответ

0

У вас может быть только одно действие на переднем плане, поэтому для вызова setAlarm 10 раз вам нужно будет пройти альтернативный маршрут. Может быть, цикл?;)

+0

Я думал о создании нового экземпляра класса, не знаю, как будет работать цикл. – SamB09

1

Не можете ли вы создать один экземпляр календаря в onCreate(), установить его параметры, затем передать экземпляр в setAlarm(), изменить экземпляр, вызвать setAlarm() и т. Д., Или я что-то упустил?

например. -

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    Calendar cal = Calendar.getInstance(); 

    cal.add(Calendar.DAY_OF_YEAR, 0); 
    cal.set(Calendar.HOUR_OF_DAY, 9); 
    cal.set(Calendar.MINUTE, 01); 
    cal.set(Calendar.SECOND, 0); 
    setAlarm(cal); 

    cal.set(Calendar.HOUR_OF_DAY, 12); 
    cal.set(Calendar.MINUTE, 30); 
    setAlarm(cal); 

//etc 

} 

public void setAlarm(Calendar cal) { 

    try { 

    Intent intent  = new Intent(Alarm.this, Alarm1.class); 
    PendingIntent sender = PendingIntent.getBroadcast(this, 1234567, intent, 0); 
    PendingIntent sende2 = PendingIntent.getBroadcast(this, 123123, intent, 0); 

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); 
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender); // to be alerted 30 seconds from now 
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sende2); // to be alerted 15 seconds from now 

    /* To show how alarms are cancelled we will create a new  Intent and a new PendingIntent with the 
    * same requestCode as the PendingIntent alarm we want to cancel. In this case, it is 1234567. 
     * Note: The intent and PendingIntent have to be the same as the ones used to create the alarms. 
     */ 
    Intent intent1  = new Intent(Alarm.this, Alarm1.class); 
    PendingIntent sender1 = PendingIntent.getBroadcast(this, 1234567, intent1, 0); 
    AlarmManager am1 = (AlarmManager) getSystemService(ALARM_SERVICE); 
    am1.cancel(sender1); 


    } catch (Exception e) { 
     Log.e(TAG, "ERROR IN CODE:"+e.toString()); 
    } 
} 
+0

Привет, Рик ive обновил мое оригинальное сообщение, чтобы дать больше идеи о том, что я пытаюсь сделать, ища на правильном пути. – SamB09

+1

Вы пытались переместить все из приведенного выше примера Alarm.OnCreate() в свой bl.setOnClickListener? Тревога a = новая сигнализация(); Календарь cal = Calendar.getInstance(); cal.add (Calendar.DAY_OF_YEAR, 0); cal.set (Calendar.HOUR_OF_DAY, 9); cal.set (Calendar.MINUTE, 01); cal.set (Calendar.SECOND, 0); a.setAlarm (cal); ... и т. Д. – RickNotFred

+0

Попробуй это позже. Благодарю. – SamB09