java每30秒在后台刷新一次Android应用程序以获取推送通知\
我正在为我的Android应用程序制作推送通知。我正在使用下面的函数获取通知。当我点击特定的按钮时,它工作正常。出于测试目的,我在按钮上执行了此操作。现在,我想每30秒运行一次此活动
代码如下:
`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秒收到一次通知。我怎样才能做到这一点?我不想为特定按钮执行此活动
# 1 楼答案
您可以使用AlarmReceiver类来实现此功能
请点击以下链接:https://www.sitepoint.com/scheduling-background-tasks-android/
参考文献:
1。创建广播接收器:
在androidmanifeat文件中声明,如下所示:
在java文件或活动类中:
在onCreate()方法中,声明并初始化意图alarmIntent:
Intent alarmIntent = new Intent(this, AlarmReceiver.class); pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
创建以下mwthod,然后将其命名为:
# 2 楼答案
我使用可运行处理程序实现了屏幕刷新。一旦我这样做了,我就用set方法更新了旧的状态