gpt4 book ai didi

android - 如何在 Android 10 中显示每日离线通知?

转载 作者:行者123 更新时间:2023-12-04 01:16:21 24 4
gpt4 key购买 nike

我想每天向用户发送离线通知。尝试了很多事情,例如:警报管理器,工作管理器,但没有运气。通知没有触发或者它们只是稍后触发。
有什么办法可以完成工作吗?
报警功能:

public void StartAlarm()
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY,23);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,0);


AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);


Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
//alarmIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);

Log.d("LOG", String.valueOf(calendar.getTimeInMillis()));

PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 156, alarmIntent, 0);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
工作经理代码:
 public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}


@NonNull
@Override
public Result doWork() {


StartAlarm();


Log.d("In worker","yes");


return Result.success();
}
工作经理司机:
public void StartPeriodicWorker()
{

final PeriodicWorkRequest periodicWorkRequest = new
PeriodicWorkRequest.Builder(MyWorker.class,24,TimeUnit.HOURS)
.addTag("Birthday")
.build();

WorkManager.getInstance(getApplicationContext()).enqueueUniquePeriodicWork("Birthday Notifier", ExistingPeriodicWorkPolicy.REPLACE, periodicWorkRequest);

}
报警接收器:
  public class AlarmReceiver extends BroadcastReceiver {

private DatabaseReference myRef;
private ArrayList<String> allPeoples;

private int numberOfPeoples;

private Context ctx;

@Override
public void onReceive(Context context, Intent intent) {

Toast.makeText(context,"In alarm receiver",Toast.LENGTH_LONG).show();

ctx = context;
initPeoples();

}

public String getCurrentDate() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("d MMMM");
String strDate = mdformat.format(calendar.getTime());
return strDate;
}


private void initPeoples() {

FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference("Users");
myRef.keepSynced(true);

myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

allPeoples = new ArrayList<>();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals("Teacher") || snapshot.getKey().equals("Staff")){
for(DataSnapshot faculty : snapshot.child("peoples").getChildren()){
String birthday = (String) faculty.child("DOB").getValue();

if(birthday.equals(getCurrentDate())) {
String member = birthday;
allPeoples.add(member);
}
}
}else{
for(DataSnapshot student : snapshot.child("peoples").getChildren()){
String birthday = (String) student.child("DOB").getValue();

if(birthday.equals(getCurrentDate())) {
String member = birthday;
allPeoples.add(member);
}
}
}
}

numberOfPeoples = allPeoples.size();

ShowNotification();

}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});

}

public void ShowNotification()
{
String CHANNEL_ID = "Channel_1453";
String CHANNEL_NAME = "Birthday Notification";

NotificationManagerCompat manager = NotificationManagerCompat.from(ctx);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}

Notification notification = new NotificationCompat.Builder(ctx, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_stat_notify)
.setContentTitle("Birthday Reminder")
.setColor(Color.GREEN)
.setContentText("Click to see who has birthday today!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setContentIntent(PendingIntent.getActivity(ctx, 0, new Intent(ctx, Birthday.class), PendingIntent.FLAG_UPDATE_CURRENT))
.build();

manager.notify(454, notification);
}
}

最佳答案

我可以看到一个可能的问题,并且可以在没有工作管理器的情况下执行此操作(假设在通知运行时设备具有健康的连接)。
我建议不要在接收器本身中建立您的网络,而是启动一个服务(如果高于 Android 8.0,则为前台服务),然后在那里完成您的工作。这是因为 android 的接收器时间限制远低于服务/前台服务。所以对我来说,在网络请求完成之前你的接收器被杀死听起来很合理,所以没有显示任何通知。
您可以在服务中显示通知,还可以安排自 setExactAndAllowWhileIdle 以来的下一个警报它本身并不是一个重复的警报。所以在你的接收器中,类似:

@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, BirthdayNotifyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(service);
} else {
context.startService(service);
}
}
然后是一个可能的服务类:
public class BirthdayNotifyService extends IntentService {

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

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

@Override
protected void onHandleIntent(@Nullable Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Build a simple notification to show if a foreground service is neccesary
Notification noti = notiBuilder.build();
startForeground(1, noti);
}

//Do your network request work here. After completed, show your birthday notification and stop the foreground service.
}
}
要停止服务,请在显示生日通知后立即使用以下命令:
stopForeground(true);
stopSelf();
更新 : 我在我的手机(小米红米 Note 8 plus)上使用了这个方法,它工作了几次,然后就停止工作了。它在股票 android 上运行良好,但并非在所有设备上都运行良好。因此,我仍然会说这不是在特定时间发送通知的可靠解决方案。

关于android - 如何在 Android 10 中显示每日离线通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63303559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com