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?
Related
I am very beginner in Android, I am creating android application, communication with Siemens PLC its working fine but if i click button only the data shown in android , I want to run this code in service I don't know how to add code(below) in service
protected String doInBackground(String... strings) {
try{
client.SetConnectionType(S7.S7_BASIC);
int res = client.ConnectTo("10.0.2.2",0,1);
if(res == 0)
{
byte[] data = new byte[4];
res = client.ReadArea(S7.S7AreaDB,1,0,2,data);
ret = "Values "+S7.GetWordAt(data,0);
}
else {
ret = "Err:"+S7Client.ErrorText(res);
}
client.Disconnect();
}
catch (Exception e)
{
ret= "Exe"+e.toString();
Thread.interrupted();
}
return "Executed";
}
Above code is working fine but this code added to service I create one service
public class MyService extends Service {
S7Client client = new S7Client();
String ret = "";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
PlcReader task=new PlcReader();
task.execute("");
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public class PlcReader extends android.os.AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... strings) {
try{
client.SetConnectionType(S7.S7_BASIC);
int res = client.ConnectTo("10.0.2.2",0,1);
if(res == 0)
{
byte[] data = new byte[4];
client.ReadArea(S7.S7AreaDB,1,0,4,data);
ret = "Values "+S7.GetWordAt(data,0);
}
else {
ret = "Err:"+S7Client.ErrorText(res);
}
client.Disconnect();
}
catch (Exception e)
{
ret= "Exe"+e.toString();
Thread.interrupted();
}
return "Executed";
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(getApplicationContext(),ret,Toast.LENGTH_LONG).show();
}
}
I added code with service but shows connection problem
See this example:-
public class ExtractService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
AsyncTask task=new AsyncTask();
task.execute();
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public class AsyncTask extends android.os.AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
}
You can call your AsyncTask from the method onStartCommand in the Service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
new MyAsyncTask().execute("stringParameter")
return START_STICKY;
}
A couple of tips:
I see that you return a String value from your AsyncTask, just avoid using
String result = new MyAsyncTask().execute("stringParameter").get()
As it will block your main thread (unless you start your async task in a different thread).
A more appropriate solution is to handle the result in the onPostExecute method in your AsyncTask (just override it)
Another thing to think about is that AsyncTask is deprecated in Android R, some good alternatives are the java.util.concurrent package and RxJava library
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;
}
}
i have a problem in my service, the service is runnig from MainActivity (i am doing test) and extends of service.
i want to use the service from foreground and background (when the app is closed) and i already have my first problem:
my service(have a counter that is displayed by LOG) is restarting when i close the app.
also i want to be able to use the service with the open app and close app, in other words to use both the Service Started and Link Service
public class MyService extends Service {
private Thread backgroundThread;
private boolean isRunning;
public MyService() {
Log.e("MyService","constructor");
}
#Override
public void onCreate() {
super.onCreate();
isRunning = false;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Log.e("onStartCommand","Servicio Llamado");
if (!this.isRunning) {
Log.e("onStartCommand","hilo iniciandose");
this.backgroundThread = new Thread(myTask);
runTask();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("onDestroy","servicio destuido");
}
private void runTask(){
this.isRunning = true;
this.backgroundThread.start();
}
private Runnable myTask = new Runnable() {
public void run() {
Log.e("myTask","hilo iniciado");
int i = 0;
do{
pauseService();
Log.e("myTask","hilo contador: "+i);
//Toast.makeText(getApplicationContext(),"CONTADOR = "+j, Toast.LENGTH_SHORT).show(); //no working :(
i++;
}while (i<10);
/*
//linea de detencion del servicio
//stopSelf();
isRunning=false;
backgroundThread.interrupt();
//backgroundThread = new Thread(myTask);
*/
Log.e("myTask","hilo cerrado");
}
};
private void pauseService(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In main Activity
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("iteraciones",10);
startService(intent);
why because the service restarts when I close the application and how can I avoid it?
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;
}
}
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.