0

I have a service chatService which gets started when MainActivity is started. i.e when app runs.

I want to run this service always even when app is closed. But unfortunately when I close my app the service stops. I want to run the newMsg() in the background always when android boots or my app is started. But it closes when app is closed.

Can someone point me in the right direction?

MainActivity.java

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intService =  new Intent(MainActivity.this, ChatHeadService.class);
       startService(intService);
    }
}

chatService.java

public class chatService extends Service {      
        public void onCreate() {
            super.onCreate();
            new newMsg(this,null,null,null).execute(); 
       }
     ...
}

newMsg.java

protected void onPreExecute() {
     super.onPreExecute();  
}   

protected JSONArray doInBackground(Object... v) {
...
}
protected void onPostExecute(JSONArray json) {
    ...
    new Handler().postDelayed(new Runnable() {
        public void run() {
            new newMsg(main,...,...,...).execute();
        }
    }, 10000);      
}

Update 1

Transferred my new newMsg(this,10,null,null,null).execute(); to onStartCommand() and added return START_STICKY.

Guess what?

It doesn't make any difference!.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    new newMsg(this,10,null,null,null).execute();
    return START_STICKY;
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Slim Shady
  • 1,045
  • 2
  • 12
  • 38
  • You are using AsyncTask, not a Service, aren't you? – Kirill K Mar 10 '15 at 19:26
  • I am calling `AsyncTask` class i.e `newMsg` from a `Service` class i.e `chatService` @KirillK – Slim Shady Mar 10 '15 at 19:37
  • Ok, right. Then follow the advice below, look for servece's onStartCommand() method and return START_STYKY from there. Also I do not hing that it is a good practice to do actual servece work in onCreate(), it should happen in onStartCommant() – Kirill K Mar 10 '15 at 20:05
  • see update 1 on question @KirillK It did not help! – Slim Shady Mar 10 '15 at 20:23
  • How are you closing your app? – Chris Stratton Mar 10 '15 at 20:29
  • @ChrisStratton I dont know what you call it but I am closing it by `long press` a button and then `swipe` `left`. – Slim Shady Mar 10 '15 at 20:34
  • That sounds like a form of stopping it which you *should expect* to kill everything - a user is only supposed to do that when the actively want to get rid of something, and not simply because they aren't making use of it right now. If you get the service settings right, android may re-start it in a new process within a few seconds-minutes, but the original is still going to get killed. – Chris Stratton Mar 10 '15 at 20:37
  • But i can see my `chatService` running but the UI stuff which i do on `newMsg`'s `onPostExecute()` is gone. It even happens when pressing a back button! @ChrisStratton – Slim Shady Mar 10 '15 at 20:43
  • Why would you be expecting UI things to happen when the app isn't displaying because you intentionally left or closed it? – Chris Stratton Mar 10 '15 at 20:44
  • I am making a `ChatHeadService` simmilar to that of `Facebook Messenger` and the thing is when app is open its fine....but when app is closed the `newMsg()` stops executing i.e fething for new data from server @ChrisStratton – Slim Shady Mar 10 '15 at 20:46
  • With your constantly changing description of what you are trying to do, and the actual code that is failing missing from your question, I don't really see this question going anywhere. – Chris Stratton Mar 10 '15 at 20:52
  • Have you taken a look at this? [Android Service need to run always][1] [1]: http://stackoverflow.com/questions/15758980/android-service-need-to-run-alwaysnever-pause-or-stop – nitzanwe Mar 10 '15 at 20:57
  • Yes but cant find anything @nitzanwe – Slim Shady Mar 11 '15 at 10:37
  • @ChrisStratton I am supposed to send the `httprequest` from `newMsg()` initiated by `chatService()` 24x7 even when app is closed! But it stops as soon as app is *killed* – Slim Shady Mar 11 '15 at 10:39

2 Answers2

1

You can use RETURN START STICKY I'm using smartphone, so can not post the code.

Search RETURN START STICKY

public class Serv extends Service {

    String t,msg1;
    int id;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
//ConnectionDetector  is custom class for detecting internet connection
//isCD() returns true if internet connection available


                if(cd.isCD())    
                   getData();

            }
        }, 0,360000);


        return START_STICKY;

    }
Umesh Chhabra
  • 268
  • 1
  • 8
  • On what version you are debugging??? Android kitkat(4.4) has issues and you can find related posts and topics of this bug. – Umesh Chhabra Mar 10 '15 at 20:41
  • I am posting my Service class. getData() method is used to fetch data from server using volley. This service runs every hour and does not stop even after exiting the application. – Umesh Chhabra Mar 11 '15 at 12:09
  • But since i am running my `getData()` method to fetch data from server every `10-15 seconds` it may cause problems. Like 1st fetching of data is not yet completed when the second executes. May cause overlapping problems. Though i have solved it @umesh – Slim Shady Mar 11 '15 at 12:18
  • Good Luck @Slim Shady – Umesh Chhabra Mar 11 '15 at 12:26
0

By replacing this on chatService.java file i was able to do the thing which i wanted. But it keeps the notification always on the top. Anybody who can tell me how to achieve this without notification on top it would be helpful and better.

chatService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    final int myID = 1234;

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);

    //This constructor is deprecated. Use Notification.Builder instead
    Notification notice = new Notification(R.drawable.ic_launcher, "Ticker text", System.currentTimeMillis());

    //This method is deprecated. Use Notification.Builder instead.
    notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);

    notice.flags |= Notification.FLAG_NO_CLEAR;
    startForeground(myID, notice);

    return super.onStartCommand(intent, flags, startId);
    //return Service.START_STICKY;
}
Slim Shady
  • 1,045
  • 2
  • 12
  • 38