如何延迟函数调用? [复制]
Posted
技术标签:
【中文标题】如何延迟函数调用? [复制]【英文标题】:How can I delay a funtion call? [duplicate] 【发布时间】:2019-03-05 01:53:19 【问题描述】: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 + "\n");
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。我不想一次用巨大的请求炸毁服务器。所以我想用随机秒数延迟调用,这样服务器就必须在给定的时间服务几个调用。
【问题讨论】:
您可以使用Handler
。
使用 System.sleep(1000);
你能帮忙吗?这是我的反应原生应用程序。我对 Java 了解不多
【参考方案1】:
timer = new Timer();
final int FPS = 3;
TimerTask updateBall = new UpdateBallTask();
timer.scheduleAtFixedRate(updateBall, 0, 1000 * FPS);
类:
class UpdateBallTask extends TimerTask
public void run()
// do work
///或
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);
【讨论】:
【参考方案2】:你可以像这样使用Handler
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run()
// your FetchNotificationData function
,timeInMiliSec);
记得将Handler
导入为android.os
,而不是java.util.logging
【讨论】:
@Ali Ahmed 的回答和你的回答有什么区别? 你说得对,我想我们俩都在同时准备答案,但他确实发送得更快 所以我只需要把这段代码放在onNotificationProcessing
函数中就可以了?基本上我对Java编码一无所知
是的,只要把这个方法放在你想调用“获取通知数据”的地方,然后把你的“获取通知数据”方法放在里面..【参考方案3】:
你可以使用handler来延迟函数调用
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
【讨论】:
以上是关于如何延迟函数调用? [复制]的主要内容,如果未能解决你的问题,请参考以下文章