0

I'd like to send http requests every N seconds. The response should be shown is some textViews. I've used timer. I guess a simple loop is not a good way.

I got error that "Can't create handler inside thread that has not called Looper.prepare()"

My test Async requests in main activity (not in timer thread) work okay, and I can see responses in textView.

My code is below:

    private void runTimer() {
    MyTimerTask myTask = new MyTimerTask();
    Timer myTimer = new Timer();
    myTimer.schedule(myTask, 3000, 1500);

}
class MyTimerTask extends TimerTask {
    public void run() {
        asyncGetRequest();
    }
}



private void asyncGetRequest(){
  new DownloadWebPageTask().execute("http://www.google.com");
}

 ....

//this method is called automatically after receiving http response
@Override
protected void onPostExecute(String result) {
    someTextView.setText("some text");
}

Thanks!!!

@@@@@@@@@@@@@@@@@@@@@@@@@@@ UPDATED!!! Now it works!!!! @@@@@@@@@@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@@@@@@@@@ UPDATED!!! Now it works!!!! @@@@@@@@@@@@@@@@@@@@@@@@@@@

I tried different examples of AlarmManagers. They don't work. But this one works (answer number 4 there) Alarm Manager Example

My code to get HTTP responses periodically is below. It works! But it works only once. (even if I comment the line with

context.unregisterReceiver( this )

So I run "runAlarm()" after getting HTTP response. So it is recursive performance. Will I have stack overflow at least? Any comments, please? Thanks!

    public void SetAlarm()
{
    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override public void onReceive( Context context, Intent _ )
        {
            asyncGetRequest();
            Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show();
            context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
        }
    };

    this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );

    PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
    AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));

    // set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
    manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent );
}

private void runAlarm() {
    SetAlarm();
}

@Override
protected void onPostExecute(String result) {
    showMyHttpResponseSomewhere();
    runAlarm();
}

And how should I replace this bla-bla-bla? Not understood the purpose of this line

this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );
Community
  • 1
  • 1
Niaz
  • 545
  • 2
  • 12
  • 21

2 Answers2

0

You can't do network request in Main UI thread. Try using AsyncTask instead.

As per your update to question:

private final static int INTERVAL = 1000 * 60 * 1; //interval is 1 minute to repeat
Handler mHandler;

Runnable mHandlerTask = new Runnable()
{
     @Override 
     public void run() {
          //call your asynctask i.e. asyncTask.execute();
          mHandler.postDelayed(mHandlerTask, INTERVAL);
     }
};

use the following to stop it

void stopRepeatingTask()
{
    mHandler.removeCallbacks(mHandlerTask);
}

use the following to restart it

void startRepeatingTask()
{
    mHandlerTask.run(); 
}
Nabin
  • 11,216
  • 8
  • 63
  • 98
  • Async requests in main activity work okay, and I can see responses in textView. But it does not work in Timer thread. Or how can I send requests evey N seconds? – Niaz Aug 10 '14 at 07:01
  • You want to run some code in every N seconds? The code is related to network request? Is that your problem? – Nabin Aug 10 '14 at 07:03
  • Yes. I'd like to send http requests each 5 seconds and I should show responses in some views. Not to use timer? Just to use loop? But such approach will eat a lot of processor time. – Niaz Aug 10 '14 at 07:05
  • Hmm, no...I need to send request inside of task, not to run task after some period. They write: "Enter AlarmManager. Rather than starting a Service that runs in the background always, this is what you want to use to schedule your code to run when your app isn't open." – Niaz Aug 10 '14 at 07:18
  • What do you want then? Run a piece of code every N minutes and the code requests network action? – Nabin Aug 10 '14 at 07:20
  • if so, i can help you for sure – Nabin Aug 10 '14 at 07:21
  • @Niaz asynctask must be loaded on the ui thread. Timertask runs on a different thread. check threading rules @ http://developer.android.com/reference/android/os/AsyncTask.html. – Raghunandan Aug 10 '14 at 07:24
  • Yes.This is polling app. It should end request to server every N minutes. Problem is that I don't know how to do it. Since timer cause errors, it seems it does not suit me. – Niaz Aug 10 '14 at 08:13
  • Hope it works fine to you. Best of luck. Any query is welcomed – Nabin Aug 10 '14 at 08:29
  • Thank you, but "mHandler.postDelayed" method cannot resolved. Maybe it is for Android 4.X. I compile for Android 3.2. It would be good if it will work on 1.6 Android... – Niaz Aug 10 '14 at 08:34
  • No i don't think so. Or else you can create a thread and sleep it for N seconds and do it. – Nabin Aug 10 '14 at 08:45
  • If you think that's your problem, make a new question related to Handler and 1.6 Android. There will be alot of people helping you. Hope I have given you some idea. Good luck – Nabin Aug 10 '14 at 08:47
  • I wonder, that there are too many obstacles in Android... Http requests in timer work okay, but I can't touch any views to show results.... – Niaz Aug 10 '14 at 09:00
  • Yes you can keep the changes to any variable and then show them from activity – Nabin Aug 10 '14 at 09:01
  • Please take a look at my update to the start message. It works with AlarmManager!!! But is it correct? – Niaz Aug 10 '14 at 11:40
0

I don't know if this is resolved, but Activity.runOnUiThread may work for you. And I can't figure out to link properly but that's a link to the documentation. :-)

enter link description here

nasch
  • 5,330
  • 6
  • 31
  • 52
  • Thank you. But I am novice in Android and the example would be really excellent.... – Niaz Aug 25 '14 at 16:27