Диспетчер тревог с Recyclerview в Android - PullRequest
0 голосов
/ 28 ноября 2018

Я хочу вызвать тревогу в фоновом режиме с несколькими arrayList пунктами, в recyclerview.Диспетчер аварийных сигналов отметит в arrayList(Database), что при совпадении даты и времени элемента с текущими датой и временем, сигнал тревоги будет вызываться, а также отправлять уведомления.Эта вся работа будет выполнена в фоновом режиме.Но в моем приложении, когда я обновляю активность, вызывается сигнал тревоги, в противном случае он не вызывается в фоновом режиме.пожалуйста, помогите мне.Спасибо!

Это мой класс фрагмента, где я звоню Alarm:

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.all_fragment,container,false);
    recyclerView = (RecyclerView) v.findViewById(R.id.recyclerviewAll);

    databaseHelper = new DatabaseHelper(getActivity());

    loadDatabase();
    setAlarm();

    return v;
}

public void loadDatabase() {

    LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());

    databaseHelper.ShowAll(arrayList);
    adapter = new AllFragmentAdapter(getActivity(), arrayList);
    adapter.setOnTapListner(new onTapListener() {
        @Override
        public void OnTapView(int position) {
            Position = position;
         //   Toast.makeText(getContext(), "" + position, Toast.LENGTH_SHORT).show();
        }
    });

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
    adapter.notifyItemChanged(Position);
    layoutManager.supportsPredictiveItemAnimations();

}


public void setAlarm() {
    Calendar calendar1 = Calendar.getInstance();
    SimpleDateFormat format, format2;
    format2 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
    String currentTime = format2.format(calendar1.getTime());
    String dbTimetoCompare = "";
    Date date1;
    long time1 = 0;

    if (arrayList.size() > 0) {
        for (int i = 0; i < arrayList.size(); i++) {
            if (arrayList.get(i).getSchedule().equals("Schedule")) {
                String date = arrayList.get(i).getDate();
                String time = arrayList.get(i).getTime();
                Name = arrayList.get(i).getName();
                Detail = arrayList.get(i).getDetail();
                String datetime = date + " " + time;
                format = new SimpleDateFormat("dd-MM-yyyy HH:mm");
                try {
                    date1 = (Date) format.parse(datetime);
                    dbTimetoCompare = format.format(date1.getTime());
                    time1 = date1.getTime();

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(System.currentTimeMillis());

                    alarmManager = (AlarmManager)getActivity().getSystemService(Context.ALARM_SERVICE);
                    Intent intent = new Intent(getContext(), MyAlarm.class);
                    intent.putExtra("CTime", currentTime);
                    intent.putExtra("DBTime", dbTimetoCompare);
                    pendingIntent = PendingIntent.getBroadcast(getActivity(), j, intent, 0);

                    if (currentTime.equals(dbTimetoCompare)){

                        for (j = 0; j < 10; ++j) {

                            alarmManager.set(AlarmManager.RTC_WAKEUP, time1, pendingIntent);

                        }
                        Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
                        Ringtone r = RingtoneManager.getRingtone(getContext(), alert);

                        if (r == null) {

                            alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                            r = RingtoneManager.getRingtone(getContext(), alert);

                            if (r == null) {
                                alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
                                r = RingtoneManager.getRingtone(getContext(), alert);
                            }
                        }
                        if (r != null)
                            r.play();

                      NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getContext());
                        mBuilder.setSmallIcon(R.drawable.ic_notifications_black_24dp);
                        mBuilder.setContentTitle("Notification Alert");
                        mBuilder.setContentText("Name: " + Name + "  Detail: " + Detail);
                        NotificationManager manager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
                        manager.notify(j, mBuilder.build());

                        Toast.makeText(getContext(), "Alarm Called", Toast.LENGTH_SHORT).show();
                    }
                    if (alarmManager != null) {
                        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                                1000 * 60 * 5, pendingIntent);
                        intentArray.add(pendingIntent);
                    }

                } catch (ParseException e) {
                    Toast.makeText(getContext(), "" + e, Toast.LENGTH_SHORT).show();
                }
            }

        }
    }
}

Это мой класс трансляции:

public class MyAlarm extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
}

1 Ответ

0 голосов
/ 30 ноября 2018

Создайте новый сервис, который запускает широковещательный приемник.

public class AlarmService extends Service {
AlarmManager alarmManager;

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    //throw new UnsupportedOperationException("Not yet implemented");
    return null;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //return super.onStartCommand(intent, flags, startId);
    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    long intervalSpan = 2 * 60 * 1000;  // set the interval span as your requirement
    Calendar calendar = Calendar.getInstance();
    Intent intentAlarm = new Intent(this, AlarmBroadCastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentAlarm, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), intervalSpan, pendingIntent);

    return START_STICKY;
}



@Override
public void onDestroy() {
    super.onDestroy();
    Intent intentAlarm = new Intent(this, AlarmBroadCastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentAlarm, 0);
    alarmManager.cancel(pendingIntent);
}
}

В файле с указанием тега приложения укажите услугу и свой широковещательный приемник

 <service
        android:name="AlarmService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>

    </service>
<receiver android:name=".receiver.AlarmBroadCastReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

на любом прослушивателе кликов, который вы можетезапустите службу как

startService(Intent(this@AlarmActivity, AlarmService::class.java))

Я надеюсь, что вы внедрили свой приемник вещания, поэтому я не использую здесь приемник вещания.Теперь либо вы можете проверить состояние внутри приемника вещания, чтобы вызвать тревогу.Когда условие истинно, просто вызовите метод, чтобы показать уведомление.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...