Execute Asyntask from timer - android

I using pushy notification in my driver android app.So my problem is that when app get notification(passenger detail),I want to execute Asyntask from Braodcast receiver after 30 seconds. I have used code given below -
final ScheduledExecutorService scheduler = Executors
.newScheduledThreadPool(1);
scheduler.scheduleWithFixedDelay(new Runnable() {
public void run() {
String cancel = preferences.getString("cancel_status", "1");
Log.d("cancell", "cancell");
if (cancel != "1")
new ConfirmRejectService(context).execute(message, "2");
}
}, 0, 5, TimeUnit.SECONDS);

You should try handler to solve your problem. It have worked for me.`
final Handler handler = new Handler();
handler.postDelayed(new Runnable()
{}

Related

To call a network API repeatedly in Android app in Foreground

I want to call a network API repeated for every 20 seconds when app is in Foreground, I tried achieving this through job Scheduler
ComponentName componentName = new ComponentName(getActivity(), TcApiLogService.class);
JobInfo jobInfo = new JobInfo.Builder(12, componentName)
.setPeriodic(20000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.build();
but job scheduler restricts from Android N to schedule jobs only once in 15 mins.
I know this can be achieved by handler but any one can pass on other better approach to solve this problem.
Handler handler = new Handler();
Runnable runnable = new Runnable(){
#Override public void run(){
//here call request
}
};
handler.postDelayed(runnable, 20000);// 20000 ms

Run volley request every 5 minutes in background android

I use Volley library to connect with server in my app. Now, I have to send request in background every 5 minutes also when app is not running (killed by user). How should I do it? With background services, AlarmManager (Google says that it isn't good choice for network operations) or something else?
Or maybe SyncAdapter will be good for it?
You can use a TimerTask with scheduleAtFixedRate in a service class to achieve this, here is an example of Service class, you can use it
public class ScheduledService extends Service
{
private Timer timer = new Timer();
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
sendRequestToServer(); //Your code here
}
}, 0, 5*60*1000);//5 Minutes
}
#Override
public void onDestroy()
{
super.onDestroy();
}
}
You can use sendRequestToServer method to connect with the server.
Here is the manifest declaration of the Service.
<service android:name=".ScheduledService" android:icon="#drawable/icon" android:label="#string/app_name" android:enabled="true"/>
To start the service from MainActivity,
// use this to start and trigger a service
Intent i= new Intent(context, ScheduledService.class);
context.startService(i);
I prefer to use Android Handler because it is executes in UI Thread by default.
import android.os.Handler;
// Create the Handler object (on the main thread by default)
Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
sendVolleyRequestToServer(); // Volley Request
// Repeat this the same runnable code block again another 2 seconds
handler.postDelayed(runnableCode, 2000);
}
};
// Start the initial runnable task by posting through the handler
handler.post(runnableCode);

Errors making async http request in timer thread

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") );
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();
}
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

How to send data from timer task to android service

I am looking for a way to send data from my timer task to service. I have seen many other post related to handlers and all but I do not want to run in my main thread
you can write a singleton class which will hold data which you want to share. This is just a way not standard.
TimerTask task = new TimerTask() {
public void run() {
if (condition) {
MySingleton.getInstance().setData(put data here);
} else {
timer.cancel();
}
}
};
Timer timer = new Timer();
timer.schedule(task, 1000, 1000);
//then cancel timer somewhere by
timer.cancel();
then in service you can get data by some thing like this
DataType myData = MySingleton.getInstance().getData();

Android Background Network service

I am developing an XMPP chat client.I am using Background service to connect to network XMPP server.however when i start the server it gives Network on UI thread Exception.
when i downgrade the Android SDK to 8 it gives ANR exception
I tried starting the Service from onCreate method of the SPlash screen.
Runnable runnable = new Runnable() {
#Override
public void run() {
Intent serviceIntent=new Intent();
serviceIntent.setClass(getApplicationContext(), SeetiService.class);
startService(serviceIntent);
}
};
new Thread(runnable).start();
Thread serviceThread=new Thread()
{
public void run()
{
Intent serviceIntent=new Intent();
serviceIntent.setClass(getApplicationContext(), SeetiService.class);
startService(serviceIntent);
}
};
serviceThread.start();
But i still get the Same network on Main UI thread.
Can some one help?
Thanks
It seems that you are trying to start two Service simultaneously.AFAIK You can not start it with above piece of code.But i will show why you are facing ANR.
Intent serviceIntent=new Intent();
serviceIntent.setClass(getApplicationContext(), SeetiService.class);
startService(serviceIntent);
The above code is supposed to run on UI thread.and if you want to run it from another thread you must embedd it into runOnUiThread.So your block should look like.
Runnable runnable = new Runnable()
{#Override
public void run()
{
runOnUiThread(new Runnable()
{
public void run()
{
Intent serviceIntent = new Intent();
serviceIntent.setClass(getApplicationContext(), SeetiService.class);
startService(serviceIntent);
}
});
}
};
new Thread(runnable).start();

Categories

Resources