有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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


共 (2) 个答案

  1. # 1 楼答案

    您可以使用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. androidmanifeat文件中声明,如下所示:

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

    2. java文件活动类中:

      onCreate()方法中,声明并初始化意图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();
      }
      
  2. # 2 楼答案

    我使用可运行处理程序实现了屏幕刷新。一旦我这样做了,我就用set方法更新了旧的状态