简体   繁体   English

每隔X分钟重复一次Android代码

[英]Repeat Android code every 'X' minutes

I know this question was already made like 10 times here but I keep having problems to solve it, as I'm very newbie with Android. 我知道这个问题在这里已经被提出过十次了,但是我仍然很难解决这个问题,因为我是Android的新手。

I was bored and I had the idea of making an app for printing a list with last TeamSpeak3 connections of my clan server. 我很无聊,我想到了制作一个应用程序来打印氏族服务器的最新TeamSpeak3连接列表的想法。 The "server-side" job is already done, as I made a Java program that prints last connections in a TXT file ( ingenium.zapto.org/joins.txt ). 当我制作了一个在TXT文件( ingenium.zapto.org/joins.txt )中打印最后连接的Java程序时,“服务器端”工作已经完成。 Now, I just want to make an Android app to print the content of that TXT file every 'X' minutes, for example, each 10. 现在,我只想制作一个Android应用来每隔X分钟(例如每10分钟)打印一次TXT文件的内容。

I already have the code to access the TXT file and print it, but I'm not being able to make it re-print the list every 10 minutes. 我已经有了访问TXT文件并打印的代码,但无法使其每10分钟重新打印一次列表。 I know there are tools like AlarmManager, Handlers, Timers... but I'm very confussed, I don't know what is the best one to use in this case and, more important, I don't know how to make them work in my code. 我知道有一些工具,例如AlarmManager,Handlers,Timers ...,但我非常困惑,我不知道在这种情况下最好使用什么工具,更重要的是,我不知道如何制作它们用我的代码工作。

MainActivity.java MainActivity.java

package org.zapto.ingenium.fetchurl;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {

private TextView txtJoins;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtJoins = (TextView)findViewById(R.id.TxtJoins);

    FetchURL fu = new FetchURL();

    fu.Run("http://192.168.0.10/joins.txt");

    String o = fu.getOutput();

    txtJoins.setText("Last connections: \n" + o);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

FetchURL.java FetchURL.java

package org.zapto.ingenium.fetchurl;

/**
 * Created by Martin on 18/01/2015.
 */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

public class FetchURL {

private String output;
private String url;

public FetchURL()
{
    output = "";
}

public String getOutput()
{
    return output;
}


public void Run(String u)
{
    url = u;
    Thread t =  new Thread() {

        public void run() {

            URL textUrl;
            try {

                textUrl = new URL(url);

                BufferedReader bufferReader = new BufferedReader(new InputStreamReader(textUrl.openStream()));

                String StringBuffer;
                String stringText = "";
                while ((StringBuffer = bufferReader.readLine()) != null) {
                    stringText += "\n" + StringBuffer;
                }
                bufferReader.close();

                output = stringText;

            } catch (Exception e) {
                // TODO Auto-generated catch block
                //e.printStackTrace();

                output= e.toString();
            }

        }
    };

    t.start();
    try {
        t.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}

activity_main.xml activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LytContenedorSaludo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView android:id="@+id/TxtJoins"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

</LinearLayout>

In summary, I want to repeat this 3 lines of code (MainActivity.java): 总之,我想重复这三行代码(MainActivity.java):

    fu.Run("http://192.168.0.10/joins.txt");

    String o = fu.getOutput();

    txtJoins.setText("Last conections: \n" + o);

every 10 minutes, for example. 例如,每10分钟一次。

After completing your code use a Handler which will execute this all again after 10 minutes? 完成代码后,使用处理程序,该处理程序将在10分钟后再次执行所有操作吗?

handlerTimer.postDelayed(new Runnable(){
    public void run() {
      // do something             
  }}, 600000);

//1000 = 1 sec // 60000 = 60 sec(1 minute) // 600000 = 600 sec (10 minutes) // 1000 = 1秒// 60000 = 60秒(1分钟)// 600000 = 600秒(10分钟)

You could add a Thread and have it repeat this task every 10 minutes. 您可以添加一个Thread ,让它每10分钟重复一次此任务。 Something like the following would work. 类似以下内容将起作用。 First declare the new Thread : 首先声明新Thread

public class MainActivity extends ActionBarActivity {

private TextView txtJoins;
private Thread repeatTaskThread;

@Override
protected void onCreate(Bundle savedInstanceState) {

    // Rest of code...

Then create a simple method which contains your new Thread : 然后创建一个包含新Thread的简单方法:

private void RepeatTask()
{
    repeatTaskThread = new Thread()
    {
        public void run()
        {
            while (true)
            {

                FetchURL fu = new FetchURL();
                fu.Run("http://192.168.0.10/joins.txt");
                String o = fu.getOutput();
                // Update TextView in runOnUiThread
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        txtJoins.setText("Last connections: \n" + o);
                    }
                });
                try
                {
                    // Sleep for 10 minutes
                    Thread.sleep(600000)
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        };
    };
    repeatTaskThread.start();
}

And lastly, call your method at the end of onCreate() : 最后,在onCreate()的末尾调用您的方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Rest of code...

    RepeatTask();
}

10min in 10min run the instruction http://developer.android.com/reference/android/os/CountDownTimer.html 在10分钟内10分钟内运行指令http://developer.android.com/reference/android/os/CountDownTimer.html

new CountDownTimer(10000, 1000) {

     public void onTick(long millisUntilFinished) {

     }

     public void onFinish() {
        fu.Run("http://192.168.0.10/joins.txt");
        String o = fu.getOutput();
        txtJoins.setText("Last conections: \n" + o);
        .start();
     }
  }.start();

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

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