Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我如何每1分钟执行一个方法来更新我的应用程序(Android Studio)_Java_Android - Fatal编程技术网

Java 我如何每1分钟执行一个方法来更新我的应用程序(Android Studio)

Java 我如何每1分钟执行一个方法来更新我的应用程序(Android Studio),java,android,Java,Android,我有一个非常简单的问题,我正在尝试每1分钟用数据库中的数据更新我的应用程序。我有一个名为“SendRequest”的方法,它从我的数据库中收集数据 如何每1分钟执行一次此方法?我不知道从哪里开始 谢谢 你可以这样做: class MyClass{ public static void main(String[] args){ while(true){ Thread.sleep(60000); SendRequest();

我有一个非常简单的问题,我正在尝试每1分钟用数据库中的数据更新我的应用程序。我有一个名为“SendRequest”的方法,它从我的数据库中收集数据

如何每1分钟执行一次此方法?我不知道从哪里开始


谢谢

你可以这样做:

class MyClass{
    public static void main(String[] args){
        while(true){
            Thread.sleep(60000);
            SendRequest();
        }
    }
}

首先将其添加到您的清单中

    <receiver android:name=".NetWatcher" >
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>

    <service
        android:name=".location_service"
        android:enabled="true" >
    </service>
}

公共类NetWatcher扩展了BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {

    //start service

           Intent in = new Intent(context, location_service.class);
           context.startService(in);


}
}

之后,在onstart命令中编写您的方法。第一次从你的主要活动开始服务

Intent in=新的Intent(上下文、位置和服务类); 上下文。startService(in)


它还将运行后台模式。

它在android中工作

将sendRequest方法放入线程中

protected void onCreate(Bundle savedInstanceState)
{
   Handler customHandler = new Handler();
   customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable() {

           public void run() {


                //enter "sendRequest" method here 

                }



               customHandler.postDelayed(this, 60000);//you can put 60000(1 minut)

           }



       };

使用alarmManager,上面的代码将在每分钟发送请求,或者如果您从服务器调用任何服务/Api,您可以使用cron JobThank,我现在将修复它
protected void onCreate(Bundle savedInstanceState)
{
   Handler customHandler = new Handler();
   customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable() {

           public void run() {


                //enter "sendRequest" method here 

                }



               customHandler.postDelayed(this, 60000);//you can put 60000(1 minut)

           }



       };