0

Я пытаюсь использовать alarmManager и pendingIntent, чтобы мои пользователи могли установить время, в течение которого в моем приложении произойдет определенное событие. Однако BroadcastReceiver запускается в конце события onClick, а не в указанное время, которое я только что установил. Это должно быть просто, но я этого не вижу. Код ниже.AlarmManager с ожидающимIntent: заданное время не регистрируется должным образом

public class MainActivity extends Activity implements View.OnClickListener { 
PendingIntent pendingIntent; 
BroadcastReceiver broadcastReceiver; 
AlarmManager alarmManager; 
TextView tvHours, tvMins; 
int iHours = 23; 
int iMins = 15; 
int iSecs = 0; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    initiateBroadcastReceiver(); 
    findViewById(R.id.the_button).setOnClickListener(this); 

    tvHours = (TextView) findViewById(R.id.Hours); 
    String szHours = Integer.toString(iHours); 
    tvHours.setText(szHours); 

    tvMins = (TextView) findViewById(R.id.Mins); 
    String szMins = Integer.toString(iMins); 
    tvMins.setText(szMins); 
} 

private void initiateBroadcastReceiver() { 
    broadcastReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      Toast.makeText(MainActivity.this, "This is the alarm event!", Toast.LENGTH_LONG).show(); 
     } 
    }; 
    registerReceiver(broadcastReceiver, new IntentFilter("pending event")); 
    pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("pending event"), 0); 
    //PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, activate, 0); 
    alarmManager = (AlarmManager)(this.getSystemService(Context.ALARM_SERVICE)); 
} 

@Override 
public void onClick(View v) { 
    String szHours=tvHours.getText().toString(); 
    int iHourTemp = Integer.parseInt(szHours); 
    if (iHourTemp < 24){ 
     iHours = iHourTemp; 
    }else{ 
     Toast.makeText(MainActivity.this, "Please enter an hour value between 0 and 23.", Toast.LENGTH_LONG).show(); 
    } 

    String szMins=tvMins.getText().toString(); 
    int iMinTemp = Integer.parseInt(szMins); 
    if (iMinTemp < 60){ 
     iMins = iMinTemp; 
    }else{ 
     Toast.makeText(MainActivity.this, "Please enter an minute value between 0 and 60.", Toast.LENGTH_LONG).show(); 
    } 

    Calendar cal = Calendar.getInstance(); 
    cal.set(Calendar.HOUR_OF_DAY, iHours); 
    cal.set(Calendar.MINUTE, iMins); 
    cal.set(Calendar.SECOND, iSecs); 
    alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent); 

    Toast.makeText(MainActivity.this, "Event is now set for " +iHours+":"+iMins, Toast.LENGTH_LONG).show(); 
} 

@Override 
protected void onDestroy() { 
    alarmManager.cancel(pendingIntent); 
    unregisterReceiver(broadcastReceiver); 
    super.onDestroy(); 
    } 
} 
+1

Если срабатывает сигнализация сразу, то вы дали дату/время в прошлом. Вам нужно учитывать возможность того, что выбранное время прошло уже сегодня. –

ответ

0

Вы должны предоставить разрешение на прием и разрешение на обслуживание в файле манифеста андроида. вы выполните этот шаг для диспетчера аварийных сигналов.

Шаг1: Вы делаете AlarmReceiver класс

public class AlarmReceiver extends BroadcastReceiver { 
@Override 
public void onReceive(Context context, Intent intent) { 
    Intent service1 = new Intent(context, AlarmService.class); 
    Bundle extras = intent.getExtras(); 
    String notification_msg = extras.getString("bookName"); 
    service1.putExtra("bookName",notification_msg); 
    context.startService(service1); 

} 
} 

Шаг2: Вы делаете новый класс обслуживания, его имя AlarmService

public class AlarmService extends IntentService { 

private static final int NOTIFICATION_ID = 1; 
private NotificationManager notificationManager; 
private PendingIntent pendingIntent; 


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


@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    return super.onStartCommand(intent, flags, startId); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    // don't notify if they've played in last 24 hr 
    Context context = this.getApplicationContext(); 
    notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 
    Intent mIntent = new Intent(this, MainActivity.class); 
    Bundle bundle = new Bundle(); 
    bundle.putString("", "test"); 
    mIntent.putExtras(bundle); 
    pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_UPDATE_CURRENT); 

    Bundle extras = intent.getExtras(); 
    String notification_msg = extras.getString("bookName"); 

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 
    builder.setContentIntent(pendingIntent) 
      .setSmallIcon(R.mipmap.logo_home) 
      .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.logo_home)) 
      .setContentTitle(getResources().getString(R.string.app_name)) 
      .setDefaults(Notification.DEFAULT_SOUND).setAutoCancel(true) 
      .setContentText(notification_msg); 

    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
    notificationManager.notify(NOTIFICATION_ID, builder.build()); 


} 
} 

Step3 где вы хотите установить сигнализацию вызова, сделать этот код

 Calendar calendar = Calendar.getInstance(); 
calendar.set(Calendar.DAY_OF_WEEK, lDay); 
      calendar.set(calendar.HOUR_OF_DAY, Integer.parseInt(hours[0])); 
      calendar.set(Calendar.MINUTE, Integer.parseInt(hours[1])); 
      calendar.set(Calendar.SECOND, 0); 
      calendar.set(Calendar.MILLISECOND, 0); 

      Date date = calendar.getTime(); 
      System.out.println(calendar.getTime()); 
      long sdl = calendar.getTimeInMillis(); 

      Intent alarmIntent = new Intent(context, AlarmReceiver.class); 
      alarmIntent.setData(Uri.parse("custom://" + Your Passing data)); 
          PendingIntent pendingIntent = PendingIntent.getBroadcast(context, index, alarmIntent, 0); 
      alarmManager.set(AlarmManager.RTC, sdl, pendingIntent); 
      index++; 

Шаг 4: предоставить разрешение в файле манифеста, как этот

<receiver android:name="com.sk.yman.utils.AlarmReceiver" android:enabled="true"/> 
    <service android:name="com.sk.yman.utils.AlarmService" /> 

для получения дополнительной помощи вам следовать этому примеру

http://javatechig.com/android/repeat-alarm-example-in-android

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