asynctask not working when app is closed - android

I am currently working on a video conferencing app, what I want to achieve is that when someone calls me and upon receiving their call I closed the app by swiping it from recent apps, and then I want to notify the caller by rejecting the call when the app is closed from recent apps
public class RecentAppService extends Service {
private static final String TAG = "RecentAppStatus";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand()");
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(TAG, "onTaskRemoved()....!!!!!!!!!!");
Boolean callactive= AppsharedPreference.getAppPrefrerence(this)
.readBooleanData("callingactive");
Log.i(TAG, "onTaskRemoved()....!!!!!!!!!! Callactive ::::"+callactive);
if(callactive){
NotificationManager nManager = ((NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE));
nManager.cancelAll();
rejectCall();
}
Intent restartService = new Intent(getApplicationContext(), this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() +1000, restartServicePI);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
#Override
public void onLowMemory() {
super.onLowMemory();
Log.i(TAG, "onLowMemory()");
}
public void rejectCall(){
AsyncTaskRunner runner = new AsyncTaskRunner(this);
runner.execute();
}
}
I have added the above Sticky service to perform the tasks when someone closes my app from recent apps,i have also added the below code that contains Asynctask to the Service to perform the reject call function
class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
private Context mcontext;
public AsyncTaskRunner(Context mContext) {
this.mcontext=mContext;
}
#Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
String mUserHash= AppsharedPreference.getAppPrefrerence(mcontext)
.readStringData("mUserHash");
String rejectApi= AppsharedPreference.getAppPrefrerence(mcontext)
.readStringData("rejectApi");
String apiToken= AppsharedPreference.getAppPrefrerence(mcontext)
.readStringData("apiToken");
String room= AppsharedPreference.getAppPrefrerence(mcontext)
.readStringData("room");
String callId= AppsharedPreference.getAppPrefrerence(mcontext)
.readStringData("callId");
ApiCallData apiCallData = new ApiCallData(rejectApi, apiToken, room, callId,mUserHash);
WebService.getWebservice().rejectCall(mcontext, apiCallData, new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.i(TAG, "onTaskRemoved()....!!!!!!!!!! Result"+result);
}
});
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
Log.i(TAG, "onTaskRemoved()....!!!!!!!!!! Result"+result);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
Everything works fine and the call gets disconnected correctly at the callerside when the application is not in foreground but when the app is open,then task is not achieved in Asynctask i.e, Asynctask stops when app is closed.. I am newbie to Android ,Thank you

You can use FirebaseJobDispatcher to perform some action even if app is closed.
to use FirebaseJobDispatcher first you need to create a Job , which will be something like this :-
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
.setService(SyncJobScheduler.class)
.setTrigger(Trigger.executionWindow(0, 0))
.setTag("Set_your_unique_tag_here")
.setReplaceCurrent(false)
.build();
dispatcher.mustSchedule(myJob);
Put this above code where you want to start any task / perform any specific task
and then you can create your Scheduler class like this :-
public class SyncJobScheduler extends JobService {
#Override
public boolean onStartJob(final JobParameters job) {
new Thread(new Runnable() {
#Override
public void run() {
try {
if (("Set_your_unique_tag_here").equalsIgnoreCase(job.getTag())) {
//PERFORM YOUR TASK HERE_ WHICH YOU WANT TO RUN IN ASYNCTASK OR SERVICE
//IT WILL RUN EVEN IF APP IS IN BACKGROUND /CLOSED
}
} catch (Throwable ignored) {
}
}
}).start();
return false;
}
#Override
public boolean onStopJob(JobParameters job) {
return false;
}
}

Related

Service stop working when turn on /of wifi many time

Service stop working when turn on /of Wi-Fi many time, when I start service do counter 1,2,3 etc or any thing then turn on /of Wi-Fi many time the service stops working ,I have BroadcastReceiver class doing start service, no exceptions , error appear , only I sent one message to phone to start service..
This is the code inside BroadcastReceiver:
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Intent recorderIntent = new Intent(context, Start2.class);
context.startService(recorderIntent);
}
This My Start2 Service:
public class Start2 extends Service {
private static final String TAG = Start2.class.getSimpleName();
int mStartMode;
#Override
public void onDestroy() {
Log.d(TAG, "Stop Service onDestroy");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
final Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
int i = 0 ;
#Override
public void run() {
try{
//do your code here
Log.d(TAG, "Start Service Repeat Time.. " + i);
i++;
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed( this, 5000 );
}
}
};
handler.postDelayed(runnable, 1000 );
return null;
}
};
task.execute();
return mStartMode;
}
}

Aws TransferManager stops when i force close my application

I am downloading objects(Videos) from aws s3 bucket. Once i call :
TransferManager transferManager = new TransferManager(s3client);
GetObjectRequest getRequest = new GetObjectRequest(bucket, entity.getName());
String s="";
download = transferManager.download(bucket, entity.getName(), f);
all the objects are downloading at background by default even if i exit my application or put my app on background.
BUT if u force close (means i long press my home button and close my application from running list)my application all the objects stops downloading
What are the ways to make downloading running at back even if application stops...
I tried with service as well:
public class MyDownloadingService extends Service {
public static Download download;
File f;
public static ArrayList<DownloadEntity> downloadList;
public class LocalBinder extends Binder {
public MyDownloadingService getService() {
return MyDownloadingService.this;
}
}
private final LocalBinder mBinder = new LocalBinder();
#Override
public void onCreate() {
super.onCreate();
// downloadList=new ArrayList<DownloadEntity>();
//Toast.makeText(this, "Service Created", 300);
}
#Override
public void onDestroy() {
super.onDestroy();
//Toast.makeText(this,"Service Destroy",300);
}
#Override
public void onLowMemory() {
super.onLowMemory();
//Toast.makeText(this, "Service LowMemory", 300);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Toast.makeText(this,"task perform in service",300);
if (intent!=null) {
String bucket = "", object = "", file = "";
if (intent.getExtras() != null) {
if (intent.getExtras().getString("bucket") != null) {
bucket = intent.getExtras().getString("bucket");
}
if (intent.getExtras().getString("object") != null) {
object = intent.getExtras().getString("object");
}
if (intent.getExtras().getString("file") != null) {
file = intent.getExtras().getString("file");
}
new downloader(bucket, object, file).execute();
}
}
return android.app.Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public static void getList(){
if (downloadList!=null) {
SoapCostants.downloadList = downloadList;
}
}
public class downloader extends AsyncTask<String, String, String> {
String bucket,object;
String file;
public downloader(String bucket,String object,String file) {
this.object=object;
this.file=file;
this.bucket=bucket;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
File f=new File(file);
// Toast.makeText(this,"Service start",300);
TransferManager transferManager = new TransferManager(S3Getter.s3client);
try {
GetObjectRequest getRequest = new GetObjectRequest(bucket, object);
String s="";
download = transferManager.download(bucket, object, f);
DownloadEntity entity2=new DownloadEntity();
entity2.setKey(object);
entity2.setValue(download);
if (downloadList==null){
downloadList=new ArrayList<DownloadEntity>();
}
SoapCostants.downloadList.add(entity2);
downloadList.add(entity2);
for (int i = 0; i < SoapCostants.downloadedList.size(); i++) {
//SoapCostants.downloadedList
if (object.equalsIgnoreCase(SoapCostants.downloadedList.get(i).getName())) {
SoapCostants.downloadedList.get(i).setIsDownloading("yes");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
}
i used start_sticky for services. But if my application was in background for long time it gets closed. or when i force close my application it gets closed.
i checked it by calling getList() of service class above. But it returns null.
The TransferManager is hosted in your application. Once the application is killed, everything it owns will be killed too, TransferManager included. When TransferManager is killed, it invokes shutdown() in finalized() to terminate all transfers running in its thread pool. If you really want it to continue to run, then you'd better try Service which can survive upon application termination. See http://developer.android.com/guide/components/services.html for more details.

App killed onBackPressed android

I start a Service from an activity that gets messages from service and shows in a Dialog. When I click back or Home button, app is killed. And app is not found in the multitasking area. I didn't write any code on onBackPressed(). How may I rectify this issue? Service Code.
public class BleepService extends Service{
String gotAlert;
Context context;
String drAlert=null;
public static boolean status = false;
public static final String TAG = BleepService.class.getSimpleName();
int counter = 0;
static final int UPDATE_INTERVAL = 5000;
private Timer timer = new Timer();
String resServer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("SERVICE", "COMES TO THE ON STARTCOMMAND");
doRepeat();
//return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
private void doRepeat() {
Log.i("SERVICE", "COMES TO THE DOREPEAT METHOD");
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
new GetStatus().execute();
}
}, 1000, UPDATE_INTERVAL);
}
class GetStatus extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
resServer = sh.makeServiceCall(Urllist.urlGetPagerStatus, ServiceHandler.GET);
while(resServer.equals("1"))
{
status = true;
resServer = sh.makeServiceCall(Urllist.urlGetMsg, ServiceHandler.GET);
}
return resServer;
}
#Override
protected void onPostExecute(String result) {
Log.i("SERVICE", "COMES TO THE GetStatus AsyncTask Class");
super.onPostExecute(result);
if(!result.equals("0"))
{
Intent i = new Intent("com.bleep.DR_ALERT_MESSAGE");
i.putExtra("msg", result);
sendBroadcast(i);
}else{
Toast.makeText(getApplicationContext(), "No New Message", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onDestroy() {
//timer.cancel();
//super.onDestroy();
/*if (timer != null){
timer.cancel();
}*/
}
}
Make sure your Service returns START_STICKY in its onStartCommand. This way OS will restart it if it ever gets killed.
It is legal for an app to be killed by the Android any time while the app is in the background.
However, OS very rarely kills Services. Are you sure you do not somehow kill it yourself, maybe, due to some bug?

AsynchTask should not stop when I terminates Application

I am making AsynkTask within Service like this
public class MyService extends Service {
private final IBinder mBinder = new LocalBinder();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v("log_tag", "Service started");
ReceiveAsyncTask receiveATask = new ReceiveAsyncTask();
receiveATask.execute();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.v("log_tag", "onBind");
return mBinder;
}
public class LocalBinder extends Binder {
MyService getService() {
return MyService.this;
}
}
class ReceiveAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
taskDummy();
return null;
}
#Override
protected void onPreExecute() {
Log.v("log_tag", "onPreExecute");
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
Log.v("log_tag", "onPostExecute");
super.onPostExecute(result);
}
#Override
protected void onCancelled() {
Log.v("log_tag", "onPostExecute");
super.onCancelled();
}
}
private void taskDummy() {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("log_tag", "taskDummy");
}
}
/** method for clients */
public int getRandomNumber() {
Log.v("log_tag", "inner Method called");
return 100;
}
}
when I am running the application it starting to print "taskDummy" every two second as expected, when I close application by prssing Back buttin still log printing continue as expected, but when I removed application from recent apps stack it stopped printing this should not happen I want my asynch task continue in this situation. even I can see my service is running from setting. please advise me.
You need to explicitly call of asyncTaskObject.cancel(true); in onDestroy of your Activity(Or your event whenever you want.)
And then rewrite your while loop logic , something like that:
// Create this variable is Your Asyantask class.
private boolean isRunning = true;
#Override
protected void onCancelled() {
isRunning = false;
}
#Override
protected String doInBackground(Void... params) {
while (isRunning ) {
// Your processing
}
return null;
}
It's a known bug: swiping the service out from recent apps destroys it.
Try following solution.

Android service thread making web request is blocking UI

First I will explain the current situation.
I've 2 different threads in 2 services(read from usb port service and make web requests service). I'm starting them in onCreate of my activity like:
serialServiceIntent = new Intent(NDKSerialActivity.this, SerialService.class);
startService(serialServiceIntent);
webServiceIntent = new Intent(NDKSerialActivity.this, RecordWebService.class);
startService(webServiceIntent);
There is nothing wrong with serial service but in RecordWebService when I make a request my gui stops until response comes.
The code is like that:
public class RecordWebService extends Service
{
public static final String SERVER_ADDRESS = "http://192.168.1.100:8080/MobilHM/rest";
private static final String TAG = RecordWebService.class.getSimpleName();
private RecordWebThread recordWebThread;
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
recordWebThread = new RecordWebThread(true);
recordWebThread.start();
}
#Override
public void onDestroy()
{
super.onDestroy();
Log.i(TAG, "RecordWebService Destroyed");
}
#Override
public IBinder onBind(Intent intent)
{
return null;
}
}
and
public class RecordWebThread extends Thread
{
private static final String TAG = RecordWebThread.class.getSimpleName();
public boolean always;
public RecordWebThread(boolean always)
{
this.always = always;
}
#Override
public void run()
{
PatientRecord patientRecord = new PatientRecord();
while (always)
{
RestClient restClient = new RestClient(RecordWebService.SERVER_ADDRESS + "/hello");
try
{
restClient.execute(RequestMethod.GET);
}
catch (Exception e1)
{
Log.e(TAG, "", e1);
}
Log.i(TAG, "Server Response Code:->" + restClient.getResponseCode());
Log.i(TAG, "Server Response:->" + restClient.getResponse());
try
{
sleep(4 * 1000);
}
catch (InterruptedException e)
{
Log.e(TAG, "Web service interrupted", e);
}
}
}
}
Also I've tried to remove sleep part and make the thread to run with timer and timer task like:
public void sendRecord()
{
scanTask = new TimerTask()
{
public void run()
{
handler.post(new Runnable()
{
public void run()
{
RestClient restClient = new RestClient(RecordWebService.SERVER_ADDRESS + "/hello");
try
{
restClient.execute(RequestMethod.GET);
}
catch (Exception e1)
{
Log.e(TAG, "", e1);
}
Log.i(TAG, "Server Response Code:->" + restClient.getResponseCode());
Log.i(TAG, "Server Response:->" + restClient.getResponse());
}
});
}
};
t.schedule(scanTask, 1000, 4000);
}
but no luck, my gui hangs when it comes to restClient.execute .
You can find RestClient.java # http://www.giantflyingsaucer.com/blog/?p=1462
How can I make my requests not block my gui thread?
Edit:
public void sendRecord()
{
scanTask = new TimerTask()
{
public void run()
{
RestClient restClient = new RestClient(RecordWebService.SERVER_ADDRESS + "/hello");
try
{
restClient.execute(RequestMethod.GET);
}
catch (Exception e1)
{
Log.e(TAG, "", e1);
}
Log.i(TAG, "Server Response Code:->" + restClient.getResponseCode());
Log.i(TAG, "Server Response:->" + restClient.getResponse());
}
};
t.schedule(scanTask, 1000, 4000);
}
Without handler, I call this in onCreate of my activity but still ui hanging.
Or you can use an IntentService which will handle the thread issues for you.
This is an example class:
public class MyService extends IntentService {
public MyService() {
super("MyService");
}
public MyService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent arg0) {
//Do what you want
}
}
Then you just call:
Intent intent = new Intent(getApplicationContext(),MyService.class);
startService(intent);
Edit:
To repeat the same thing every 4 seconds you should do something like this:
PendingIntent serviceIntent= PendingIntent.getService(context,
0, new Intent(context, MyService.class), 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
long intervalInSec = 4;
am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, intervalInSec*1000, serviceIntent)
;
In your code (2d version) happens next: You create thread, and it asks UI thread to do some net interaction. Just exclude handler.post(...) while executing request. Later you can use this for simple runnable for updating your UI with results of request.

Categories

Resources