我正在为我的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秒获取一次通知。我怎样才能做到这一点?我不想为特定按钮执行此活动。
答案 0 :(得分:1)
您可以使用 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();
}
}
在 AndroidManifeast 文件中声明 ,如下所示:
<receiver android:name=".AlarmReceiver"></receiver>
在 java文件或活动类中:
在 onCreate()方法中,声明并初始化Intent alarmIntent:
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
在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();
}
答案 1 :(得分:0)
我使用 Runnable Handler 实现了屏幕刷新。一旦我这样做,我用set方法更新了旧状态。