0

I have a simple Android app. I am getting HTML elements from a website (article count from wikipedia) by use of JSOUP. I am getting article count on button click RefreshBtn() and show in a textview tv1 as shown below:

public class MainActivity extends ActionBarActivity {

    String URL = "https://en.wikipedia.org";
    Element article;
    TextView tv1;
    ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);   
        tv1 = (TextView)findViewById(R.id.tv1);   
    }

    private class FetchWebsiteData extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                Document doc = Jsoup.connect(URL).userAgent("Mozilla").get();
                article = doc.select("div#articlecount > a").first();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if(article == null) tv1.setText("null!");
            else tv1.setText(article.text() + " articles found!");
            mProgressDialog.dismiss();
        }
    }

    public void RefreshBtn(View v) {
        new FetchWebsiteData().execute();
    }
...
}

I want to get article count periodically (for example in every 2 hours). Then maybe I can create push-notifications if there is a change. What is the best way to do this? I need some suggestions. Thanks.

smtnkc
  • 488
  • 2
  • 9
  • 23

1 Answers1

0

The best way is to use the internal Alarm Manager.

Alarm Manager Example

another way is to implement a second Thread:

new Thread(new Runnable()
  @Override
  public void run()
   {
    try
     {
      while(true)
       {
        Thread.sleep(100000); //milliseconds
        // Do Something
       }
     }
    catch (InterruptedException e)
     {
      e.printStackTrace();
     }
    }
 }).start();
Community
  • 1
  • 1
  • 1
    Are you sure that the second way (with a thread) is periodically? Shouldn't you add a loop inside it? – TDG Jun 17 '15 at 13:22