每隔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秒收到一次通知。我怎样才能做到这一点?我不想为特定的按钮执行此活动。

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

关注此链接:https://www.sitepoint.com/scheduling-background-tasks-android/

参考:

1.创建BroadcastReceiver:

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文件活动类中:

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

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

  • 创建以下mwethod,然后调用它:

    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();
    }
    
  • 我使用可运行处理程序实现了屏幕刷新。一旦我这样做了,我就用set方法更新了旧的状态。

    最新更新