Android Data Upload in fixed time interval - android

I have an Android application, which uploads data into web service using async tasks(P,Q,R) currently starting fired in button click. I have three tables(A,B,C) of data. Currently I upload Table A data in doInBackground in first async task(P), I call second async task(Q) in onPostExecute of first async task(P).In onPostExecute, I update my local tables with returned data and give some UI messages as well. while that functionality is existing, now I want to upload data in a fixed time interval(every 30 minutes) even though the application is closed. when the device is booting up/installing app/updating app, this process should be started.While uploading data, if the user opens the application, upload button should be disabled.I don't necessarily need a long running task that runs forever.
1.Do I need to use services instead async tasks?
and give me advice on this.

To Upload Data do as follow
I think you are pretty new to android, Rather than Asynctasks i think you should move to volley or retrofit which is very easy and very fast when compared to Asynctask
Do I need to use services instead async tasks
Since you need to upload data every 30 mins i suggest you move your code to a service within which you will upload data. Also since a service is used it will work when the app is closed also, as it runs in the background

Your Receiver class
import java.util.Timer;
import java.util.TimerTask;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class yourReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
int delay = 5000; // delay for 5 sec.5000
int period = 60000; // repeat every 1min.60000
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Intent serviceIntent = new Intent(context,UploadService.class);
context.startService(serviceIntent);
}
}, delay, period);
}
}
Your Service Class
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class UploadService extends Service {
MediaPlayer myPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.sun);
myPlayer.setLooping(false); // Set looping
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
serviceThread = new ServiceThread();
serviceThread.start();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
}
private class ServiceThread extends Thread {
#Override
public void run() {
synchronized(UploadService.class){
if(uploadStatus) {
uploadStatus = false;
uploadData();
uploadStatus =true;
}
}
}
}
}

Related

TimerTask stops firing in Service

I need to have a Service running in Android that stores a value to database every so often. How often is based on user preferences, and also if other events have happened, which can be as often as 30 seconds or up to 30 minutes.
This is not something that is hidden from the user and in fact the user should probably be aware its running. As such I think a foreground service is probably the best approach.
I have a foreground service running, with a TimerTask that calculates how often it needs to fire. That Service is 'sticky' so it should stick around and it low on resources the OS should start it back up after a while.
My problem is that the TimerTask seems to stop running after a while when the the app is backgrounded.
Here is my service:
public class TimerService extends Service {
private static final String LOG_NAME = TimerService.class.getName();
private Timer timer;
private final Handler timerHandler = new Handler();
#Override
public void onCreate() {
super.onCreate();
Notification notification = new NotificationCompat.Builder(this, "MY_APP_CHANNEL_ID")
.setContentTitle("My Timer Service")
.setContentText("Background timer task")
.setSmallIcon(R.drawable.timer)
.build();
startForeground(1, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startTimer();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
stopTimer();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void stopTimer() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
private void startTimer() {
stopTimer();
timer = new Timer();
long frequency = // calculate frequency
long delay = // calculate delay
timer.scheduleAtFixedRate(new MyTimerTask(), delay, frequency);
}
private void saveToDatabase() {
// Save some stuff to the database...
if (some condition) {
// might need to reschedule timer delay and frequency.
startTimer();
}
}
private class MyTimerTask extends TimerTask {
#Override
public void run() {
timerHandler.post(new Runnable() {
#Override
public void run() {
onTimerFire();
}
});
}
private void onTimerFire() {
try {
saveToDatabase();
} catch (Exception e) {
Log.e(LOG_NAME, "Error in onTimerFire", e);
}
}
}
}
Should this work? IE can I have a simple Timer in a foreground Service that fires continuously until that service is stopped? If so is there a bug in my code?
I chose a Timer to try to keep it simple, I only ever need one timer running and I wanted it to be able to reschedule easily. I do realize that I could try a Handler, ScheduledThreadPoolExecutor, or even an AlarmManager. I thought an AlarmManager might be overkill and a drain on resources if it is firing a ton. Not to mention rescheduling.
Why won’t it run in the background?
It is running in the background. It is not running when the device is asleep, as the CPU is powered down. In Android, "background" simply means "has no foreground UI" (activity, service with a foreground Notification).
I need to have a Service running in Android that stores a value to database every so often. How often is based on user preferences, and also if other events have happened, which can be as often as 30 seconds or up to 30 minutes.
What you want has not been practical on Android since 6.0.
I thought an AlarmManager might be overkill and a drain on resources if it is firing a ton.
That is true. However, the only way to get your existing code to work would be for you to acquire a partial WakeLock, thereby keeping the CPU running forever. This will be orders of magnitude worse for power than is AlarmManager. And AlarmManager is bad enough that each Android release, starting with 6.0, has made it progressively more difficult to use AlarmManager (or JobScheduler, or Timer and a wakelock) to do anything reliably.
You are going to need to learn what Android is and is not capable of with respect to background processing, then adjust your product plans accordingly. That subject is way too long for a Stack Overflow answer.
Here is a set of slides from a presentation that I delivered last year on this subject, with Android 8.0 in mind (use Space to advance to the next slide). You might also read:
My thoughts on Android P DP2, particularly "What’s New in the War on Background Processing"
This preview of one of my book chapters, where the section on Android 8.0 and its phase in "The War on Background Processing" happens to be included
Wakelock and doze mode
IMHO, writing an app that relies upon periodic background processing is a very risky venture nowadays.
You should use ScheduledExecutorService for the same. There can be many ways to schedule background task like Alarm Manager, JobDispatcher, Sync Adapter, Job Scheduler. I will suggest ScheduledExecutorService over them.
I have one good example of using ScheduledExecutorService in service. (Currently using in highly optimised location sync service)
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* Created by KHEMRAJ on 1/29/2018.
*/
public class SyncService extends Service {
private Thread mThread;
ScheduledExecutorService worker;
private static final int SYNC_TIME = 60 * 1000; // 60 seconds
#Override
public int onStartCommand(#Nullable Intent intent, int flags, int startId) {
startSyncService();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
stopThread();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void stopThread() {
worker = null;
if (mThread != null && mThread.isAlive()) mThread.interrupt();
}
private void startSyncService() {
if (worker == null) worker = Executors.newSingleThreadScheduledExecutor();
if (mThread == null || !mThread.isAlive()) {
mThread = new Thread(new Runnable() {
#Override
public void run() {
saveToDb();
if (worker != null) {
worker.schedule(this, SYNC_TIME, TimeUnit.MILLISECONDS);
}
}
});
mThread.start();
}
}
private void saveToDb() {
// TODO: 5/15/2018
}
}

Restarting a service in the onDestroy method

I have made an app in which a service runs in the background. But if the android system requires resources, it will stop the service. However I may still require my service to run.
Is it a bad practice to restart the service (if condition relevant to my app still holds true) in the onDestroy method of my service?
How can I make sure my service runs indefinitely (if condition relevant to my app still holds true)? Or atleast on high priority?
Probably the best you can do is use the START_STICKY flag, which tells Android to attempt to restart the service if it has stopped. Beyond that ensure that it consumes as few resources as possible, so that it is less likely to be destroyed.
Android prioritizes the UI over everything. Then processes that are related to the UI. Then processes that are consuming the least amount of resources. A Service runs in the background, so unless it has resources that are also in use on the UI or connected to the UI in some way, it should be a lower priority.
Also you cannot tell Android how to prioritize your Service (everyone would make theirs the "highest priority" right?). So it goes by how well you minimize the impact on overall resources - why kill 3 Services when it could kill 1 and regain all the resources it needs?
To help understand how to manage memory better: http://developer.android.com/training/articles/memory.html
set it START_STICKY. It Causes after killing service the service will restart again. it is my code :
android manifest :
<application
....
<service android:name=".UpdateService" />
</application>
service class :
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.....);
filter.addAction(Intent....);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
Log.i("log", "action Called");
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
receiver class :
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Log", "recevid");
}
}
in StartupActivity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Context context = getApplicationContext();
Intent service = new Intent(context, UpdateService.class);
context.startService(service);
}

killing other applications

i want to kill the sms application when it is open. for this purpose i write a service . that checks if sms application is opened. and if it is then it kills this. i am using ActivityManager class. here is my code
but when i launch sms application it nevers ends. why? is it possible ? if yes then please help.
package com.example.activitymanager;
import java.util.List;
import android.app.ActivityManager;
import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
public class Servicee extends IntentService {
ActivityManager am;
Handler handler = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
List<ActivityManager.RunningTaskInfo> list = am
.getRunningTasks(Integer.MAX_VALUE);
for (ActivityManager.RunningTaskInfo task : list) {
if (task.baseActivity.getPackageName()
.equals("com.android.mms")) {
am.restartPackage(task.baseActivity.getPackageName());
}
}
handler.postDelayed(this, 5000);
}
};
public Servicee() {
super("");
}
#Override
protected void onHandleIntent(Intent arg0) {
am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
handler.postDelayed(r, 2000);
}
}
I agree with Usman Riaz comment but keep in mind, the process id might change from device to device. I wanted to monitor the tpc traffic of a specific app and id didn't work out in the end. You'll kill some other app or crash the system.

How to wake up my App Periodically

I want to make an functionality, like reminder, in Android.
I want to start-up my app/activity, when it is not running, or its UI is invisible.
It is some-thing like same as reminder, that wakes ups the app at desired time.
I have not worked with any type of background task or service,
so I haven't any idea that what to do,
or what type of classes or demos should be studied by me?
Can any one give me some suggestions with demos or tutorials links.
Thanks, in advance.
Hi use the following code. This is service. By using pending Intent with alarm manager you can open your UI at your needed time.
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class ScheduleCheckService extends Service{
private Timer timer;
final int REFRESH=0;
Context context;
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
context=this;
//==============================================
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
handler.sendEmptyMessage(0);
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000);
//=======================================================
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
//your code here
break;
default:
break;
}
}
};
void PendingIntentmethod()
{
Intent myIntent = new Intent(context, YOURCLASS.class);
pendingIntent = PendingIntent.getActivity(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
}
}
Start the service and stop the service when you want and also dont forget to register it in manifest file.
Have a look at the Android Service class.
http://developer.android.com/reference/android/app/Service.html
From this Service you can periodically start (using a TimerTask) an Intent to open your App or just set a Notification, from which the user can open the App with the desired Activity. I would prefer the second option, because he user doesn't want an Application just to be opened at some time.
Here is a simple Service Tutorial:
http://www.vogella.com/articles/AndroidServices/article.html

Android Service stopping without being told?

I am having a weird situation where a Service that is created is stopping - sometimes. I have a entry Activity A that starts a service using bindService
// if we now have an IP address then bind ourselves to the MessageService
bindService(new Intent(this, MessagingService.class),
onMessageService,
BIND_AUTO_CREATE);
The MessageService handles kicking of Read and Send threads to handle message traffic with the app. It basically handles polling for new messages at 1 second intervals using a StatusTask and it's timer using timer.scheduleAtFixedRate.
Activity A then kicks off another Activity B that displays info to the user. For some reason that I yet to figure out, most of the time when I press the home button, the polling stops and the Service seems to have stopped. Reslecting my app from the Home recent apps list or via a notification I post when not visible brings the Activity to the foreground, but the Service seems to be gone. Making this harder to debug, about 10-20% of the time everything works great and the Message Polling service keeps plugging away.
Should I be using startService instead? The only direct relationship that the second Activity B has with the Service is that registers itself as an observer of the Read thread in order to be notified about timeouts on Reads. I am not calling stopService anywhere in my code.
public class Testservice extends Service {
private static final String TAG = Testservice.class.getSimpleName();
public Timer timer;
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service creating");
_startService();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
t.cancel();
t = null;
}
public void yourfunction()
{
}
//this will invoke the function on everysecond basis so try it if it helpsa
public void _startService(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
yourfunction();
}
});
}};
t.schedule(scanTask, 1000L, 1000L);
}
if developing using eclipse ---> try this go to DDMS that will be in the Perspective Option in Menu bar ---> select Logcat and while you are running your application just try to repeat the sequence you just mentioned above and on pressing home button just look at what is the error if at all coming during that instance and post the error so that the specific reason could be understood
Regards,
Mistry Hardik
Starting a service with bbindService makes the service lifecycle tied to the bound activities. Once your activity unbinds from the service, the service dies.
a simple service demo class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ServicesDemo extends Activity implements OnClickListener {
private static final String TAG = "AlertService";
Button buttonStart, buttonStop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.servicedemo);
buttonStart = (Button) findViewById(R.id.btnStart);
buttonStop = (Button) findViewById(R.id.btnStop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
public void onClick(View src) {
switch (src.getId()) {
case R.id.btnStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, Testservice.class));
break;
case R.id.btnStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, Testservice.class));
break;
}
}
}

Categories

Resources