Android Push-уведомления за определенное время с помощью Alarm Manager

1

Я хочу использовать push-уведомления в течение всего времени. Я использую эти коды;

Это мой класс AlarmReceiver:

public class AlarmReceiver extends BroadcastReceiver {

private static int NOTIFICATION_ID = 1;

@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager manger = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Notification notification = new Notification(R.drawable.arrrow_icon,
            "test", System.currentTimeMillis());

    PendingIntent contentIntent = PendingIntent.getActivity(context,
            NOTIFICATION_ID, new Intent(context, AlarmReceiver.class),0);

    Bundle extras = intent.getExtras();
    String title = extras.getString("title");
    String note = extras.getString("note");
    notification.setLatestEventInfo(context, note, title, contentIntent);
    notification.flags = Notification.FLAG_INSISTENT;
    notification.defaults |= Notification.DEFAULT_SOUND;
    manger.notify(NOTIFICATION_ID++, notification);

}
};

И это мой основной класс.

Intent alarmintent = new Intent (getApplicationContext(), AlarmReceiver.class); alarmintent.putExtra("title", "test"); alarmintent.putExtra("note", "тестовое сообщение"); PendingIntent sender = PendingIntent.getBroadcast(getApplicationContext(), 1, alarmintent, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);

      AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
          am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);

Если мое приложение работает, то push-уведомления работают правильно. Но когда я принудительно закрываю уведомления, они не работают. Спасибо за помощь.

Теги:
push-notification
alarmmanager
alarm

2 ответа

0

ok, тогда попробуйте использовать этот код, выведите этот код из onCreate() protected void onUserLeaveHint() {//TODO Автоматически сгенерированный метод stub super.onUserLeaveHint(); exitAppAnimate(); }

private void exitAppAnimate() {
    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> recentTasks = activityManager
            .getRunningTasks(Integer.MAX_VALUE);
    for (int i = 0; i < recentTasks.size(); i++) {
        if (i == 1
                && recentTasks.get(i).baseActivity.toShortString().indexOf(
                        getPackageName()) > -1) {
            // home button pressed
            IShomepressed = true;
            System.out.println("Home buttonpressed..........");

            // android.os.Process.killProcess(android.os.Process.myPid());
            break;
        }
    }
}  and put this if (IShomepressed) {
        IShomepressed = false;

где вы используете Ожидание намерения. Это поможет вам.

  • 0
    Извините, я не мог понять. Где я должен вызывать функцию onUserLeaveHint ()? Спасибо еще раз
  • 0
    Вы должны использовать метод onUserLeaveHint () вне метода onCreate ().
Показать ещё 1 комментарий
0

Это может вам помочь. Сначала используйте этот код для вашего класса приемника будильника

public class AlarmReceiver extends BroadcastReceiver
{
    NotificationManager nm;
    public void onReceive(Context context, Intent intent) 
    {
        Toast.makeText(context, "Log Out !!", Toast.LENGTH_LONG).show();
//      Vibrator vibrator=(Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
//      vibrator.vibrate(1000);
        nm=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        CharSequence ch="Log Out Service";
        CharSequence message="Log Out You have to login again!! ";
        Notification notif = new Notification(R.drawable.ic_launcher,
                    "You Are Logged out...", System.currentTimeMillis());
//       PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
//                  new Intent(), 0);
         Intent notifyintent=new Intent(context,AlarmManagerTestActivity.class);
         PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, 
            notifyintent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
         notif.flags |=Notification.FLAG_AUTO_CANCEL;
                  notif.setLatestEventInfo(context, ch, message, pendingIntent);
                  nm.notify(0, notif);        
         }
    }

затем введите этот код в свою деятельность

Intent intent = new Intent(your activity,AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
AlarmManagerTestActivity.this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);  
  • 0
    спасибо за ваш ответ :) это тот же результат. это работает, но когда вы принудительно останавливаете приложение из меню приложений, уведомления не работают
  • 0
    хорошо, тогда попробуйте использовать этот код,

Ещё вопросы

Сообщество Overcoder
Наверх
Меню