关于java:如何延迟函数调用?

How can I delay a funtion call?

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
public class NotificationReceivedCheckDelivery extends NotificationExtenderService {
   @Override
   protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
      OverrideSettings overrideSettings = new OverrideSettings();

      overrideSettings.extender = new NotificationCompat.Extender() {
         @Override
         public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
            // Sets the background notification color to Yellow on Android 5.0+ devices.
            return builder.setColor(new BigInteger("FFFFEC4F", 16).intValue());
         }
      };

      OSNotificationDisplayedResult displayedResult = displayNotification(overrideSettings);
    Log.d("ONES",receivedResult.payload.title);
      JSONObject AdditionalData = receivedResult.payload.additionalData;
        Log.d("Adata",AdditionalData.toString());

      String uuid= null;
      try{
        //   {"uuid":"adddd"}
          uuid = AdditionalData.getString("uuid");

      }
      catch (JSONException e){
          Log.e("Error JSON","UUID",e);
      }



                // Create Object and call AsyncTask execute Method
                new FetchNotificationData().execute(uuid);

      return true;
   }



private class FetchNotificationData extends AsyncTask<String,Void, String> {

        @Override
        protected String doInBackground(String... uuids) {
            // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            try {

                URL url = new URL("http://test.com/AppDeliveryReport?uuid="+uuids[0]);


                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line +"
"
);
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                forecastJsonStr = buffer.toString();
                return forecastJsonStr;
            } catch (IOException e) {
                Log.e("PlaceholderFragment","Error", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("PlaceholderFragment","Error closing stream", e);
                    }
                }
            }

        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.i("json", s);
        }
}
}

我想用随机秒延迟调用fetchnotificationdata函数。这是传递报告URL请求功能。只要应用程序收到来自OneSignal的通知,它就会调用URL。我不想用一个巨大的请求来炸毁服务器。所以我想用随机的秒延迟呼叫,这样服务器在给定的时间内就必须提供很少的呼叫。


可以使用处理程序延迟对函数的调用

1
2
3
4
5
6
7
8
  new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(Splash.this,"I will be called after 2 sec",
                                                              Toast.LENGTH_SHORT).show();
                    //Call your Function here..
                }
            }, 2000); // 2000 = 2 sec

您可以使用这样的处理程序

1
2
3
4
5
6
7
  Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
               // your FetchNotificationData function
            }
        },timeInMiliSec);

只需记住输入Handler作为android.os,而不是java.util.logging


1
2
3
4
 timer = new Timer();
 final int FPS = 3;
 TimerTask updateBall = new UpdateBallTask();
 timer.scheduleAtFixedRate(updateBall, 0, 1000 * FPS);

班级:

1
2
3
4
5
class UpdateBallTask extends TimerTask {
    public void run() {
        // do work
    }
}

/或/或

1
2
3
4
5
6
7
8
9
  final Handler handler = new Handler();
    final Runnable r = new Runnable() {
        public void run() {
           handler.postDelayed(this, 100);
           // do work
                handler.removeCallbacksAndMessages(null);          
        }
    };
   handler.postDelayed(r, 100);