简体   繁体   English

如何定期运行任务?

[英]How to periodically run a task?

I started building my app to send JSON strings to a server, however it is only sent when I click a button. 我开始构建我的应用程序以将JSON字符串发送到服务器,但是仅在单击按钮时才发送。 I would like it to be sent automatically after a time that is specified by the user from a TimeDialog. 我希望它在用户从TimeDialog指定的时间之后自动发送。 I was suggested to use AlarmManager or Handler, but I do not know how to implement it with my app. 建议我使用AlarmManager或Handler,但是我不知道如何在我的应用程序中实现它。 I have provided the line of code that will be executes and sends to my server. 我提供了将执行并发送到我的服务器的代码行。 Any help or suggestions? 有什么帮助或建议吗?

Code used I would like it to be run after specified time: 使用的代码我希望在指定时间后运行:

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.saveBtn:

            if (!validate())
                Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
            // call AsynTask to perform network operation on separate thread
            new HttpAsyncTask().onPostExecute("server_adress"); //was execute but changed!
            break;
    }

}

You can use Java Util Timer class to do what you want. 您可以使用Java Util Timer类来执行所需的操作。

you can see here an example. 您可以在此处查看示例。

Try to use it!!! 尝试使用它!

While an alarm manager/handler is often the best way schedule future events on Android, Google suggests using a Sync Adapter when scheduling network calls like your application synching to the server at a given interval. 虽然警报管理器/处理程序通常是安排Android上未来事件的最佳方式,但Google建议在安排网络调用(例如,应用程序以给定的间隔同步到服务器)时使用同步适配器。 The framework provides a predefined user authentication, background scheduling so that you app does not need to be running to make the call, improved battery performance, and handling the case when there is no network connectivity at the time scheduled. 该框架提供了预定义的用户身份验证,后台调度,因此您的应用无需运行就可以拨打电话,提高了电池性能以及处理了在计划的时间没有网络连接的情况。 Here's their developer page on using Synch Adapters . 这是他们的使用Synch Adapters的开发人员页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM