4

I am implementing Service for receiving push notifications in Android device. The notifications are successfully received when app is in foreground. When app is closed and its instance is cleared from task manager, notifications are not received.

I want to keep the service running at all the times and it should not stop even if the app is cleared from the task manager.

I start the service from my activity in a button click. When i click the button my service starts and it gives me Toast notification every one minute but if I press the back button then also my service is running but , as soon as i clear my app from the recent activity list which is shown on long press of home button my service is stoped and if again i start my app and check the status of the service but its not running.

I want my service to run even if my app is closed.

This is my activity class

package com.example.hello;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity {

    Button btnSer;
    int Pointer=0;
    ListView lv;
    ArrayList<String> alist=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSer=(Button) findViewById(R.id.btnstart);
        btnSer.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                //start  the service when the button is clicked
                Log.e("","status of service : "+isMyServiceRunning(MyService.class));
                //if(!isMyServiceRunning(MyService.class))
                    startService(new Intent(getApplicationContext(), MyService.class));
            }
        });

    }

    //check if the service is running
    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


}

This is my Service class.

 package com.example.hello;

import java.util.Calendar;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service{

    private Handler handlerList = new Handler(); 
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful
        Toast.makeText(getApplicationContext(), "On start command called", Toast.LENGTH_LONG).show();
         return Service.START_STICKY;
    }
    public void updateLists(){
        handlerList.postDelayed(mUpdateListTask, 1000*60);
    }
    private Runnable mUpdateListTask = new Runnable() {
        public void run() {  //will make a toast notification every 1 minute.
            Calendar cal = Calendar.getInstance();

            Log.e("","Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":");
            Toast.makeText(getApplicationContext(), "Thread executed at "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":", Toast.LENGTH_LONG).show();
           handlerList.postDelayed(this, 1000*60);
        }};
    @Override
    public void onCreate() {

        updateLists();
        Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
        Log.d("", "onCreate in service");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
        Log.d("", "onStart in service");    
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
        Log.d("", "onDestroy in service");
    }
}

also added the permission in manifest file

<uses-permission android:name="android.permission.WAKE_LOCK" />
codemaniac
  • 260
  • 2
  • 14
  • you cannot keep your service running forever, also if you are using GCM for push messages you dont need a service to listen for push messages – tyczj Jun 13 '14 at 16:42
  • What do you mean by "cleared from the task manager."? – Squonk Jun 13 '14 at 16:49
  • I noticed you returned the `START_STICKY` in the `onStartCommand`. you might want to look at this [Stackoverflow post](http://stackoverflow.com/questions/20636330/start-sticky-does-not-work-on-android-kitkat-edit-and-jelly-bean) It may or may be related and may or may not help. Also, killing the application from 'task manager' by which you mean `Setting->Apps->Running` then it will kill the service as well. The one post answer calls the `onTaskRemoved` which should restart it. – CodeMonkey Jun 13 '14 at 17:03
  • 1
    @Squonk "cleared from task manager" means to clear my app from the recent app list. We can see that list on long press of home button. – codemaniac Jun 14 '14 at 06:54

1 Answers1

0

Start it as foreground service in the activity use startforeground(intent name) and return it as sticky in the service onstartCommand() method.

bated
  • 960
  • 2
  • 15
  • 29