gpt4 book ai didi

java - 每 30 秒在后台刷新 Android 应用程序以获取推送通知\

转载 作者:行者123 更新时间:2023-11-30 10:25:47 24 4
gpt4 key购买 nike

我正在为我的 Android 应用开发推送通知。我正在使用以下功能来获取通知。当我点击特定按钮时它工作正常。出于测试目的,我在按钮上执行了此操作。现在,我想每 30 秒运行一次此 Activity 。

代码如下:

`public static void createNotification(Context mMain, boolean isLoggedIn)
{
NotificationCompat.Builder builder =
new NotificationCompat.Builder(mMain)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Items in your Cart")
.setContentText("You have some pending items in your cart")
.setDefaults(NotificationCompat.DEFAULT_SOUND)
.setAutoCancel(true);
int NOTIFICATION_ID = 12345;

Intent targetIntent = new Intent(mMain, MainActivity.class);
targetIntent.putExtra("isTrackOrder", false);
if(isLoggedIn)
targetIntent.putExtra("isLoggedIn", true);
else
targetIntent.putExtra("isLoggedIn", false);
PendingIntent contentIntent = PendingIntent.getActivity(mMain, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager nManager = (NotificationManager) mMain.getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
}`

现在我想做的是,当我运行应用程序或应用程序在后台运行时,我想调用此函数并每 30 秒获取一次通知。我怎样才能做到这一点?我不想为特定按钮执行此 Activity 。

最佳答案

您可以使用AlarmReceiver 类来实现这一点。

点击此链接:https://www.sitepoint.com/scheduling-background-tasks-android/

引用:

<强>1。创建广播接收器:

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context arg0, Intent arg1) {
// For our recurring task, we'll just display a message
Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();

}
}
  1. AndroidManifest 文件中声明 如下:

    <receiver android:name=".AlarmReceiver"></receiver>

  2. 在您的java 文件Activity 类中:

    onCreate()方法中,声明并初始化Intent alarmIntent:

Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

  1. 创建下面的 mwthod 然后调用它:

    public void startAlarm(View view) {
    manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    int interval = 10000;
    manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
    Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }

关于java - 每 30 秒在后台刷新 Android 应用程序以获取推送通知\,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45956226/

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