Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering a ContentObserver in a Android Service

Tags:

android

I am working on parental control/adult content filtering application. This app continuously monitors the calls and smses on a child's mobile and logs all the activity onto a server. For this I am starting a service (MyService.java) on BOOT_COMPLETED and in the onCreate method of the service I register a contentobserver for the callLog and sms uri ( refer to the code snippet below ) .

Now the issue is, Since I want to monitor every outgoing, incoming call s and sms I want the service to be continuously running ( without being stopped/killed) . Moreover this Service is being just used for registering content observers and not doing any other processing(its OnstartCommand method is dummy ) , so android OS kills the service after sometime. How do I ensure that the service runs continuously and keeps the contentobserver object alive ?

   
public class MyService extends Service {

    private CallLogObserver clLogObs = null;
    public void onCreate() {        
        super.onCreate();       
        try{                            
            clLogObs = new CallLogObserver(this);
            this.getContentResolver().registerContentObserver(android.provider.CallLog.Calls.CONTENT_URI, true, clLogObs);               
         }catch(Exception ex)
         {
             Log.e("CallLogData", ex.toString());
         }
    }

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

    @Override
    public void onDestroy() {   
        if( clLogObs !=null  )
        {
            this.getContentResolver().unregisterContentObserver(clLogObs);
        }
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {  
        super.onStartCommand(intent, flags, startId);           

        return Service.START_STICKY;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
like image 980
Srao Avatar asked Apr 12 '11 08:04

Srao


2 Answers

You cannot ensure your service to be running continuously on Android.

For the use-case you mention, it is better to rely on Broadcast receiver like ACTION_NEW_OUTGOING_CALL & SMS_RECEIVED.

If you feel, above supported Broadcast receivers doesn't cover all your use-cases. Use AlaramManager to periodically start your SERVICE and look into CALL_LOGS and SMS table for any change in data and take appropriate action (this may involve check marking the last visited data on CALL_LOGS and SMS table).

like image 103
Sukumar Avatar answered Sep 21 '22 15:09

Sukumar


you can set the service to run in the foreground . this will give your service a much lower chance of being killed by the OS .

read here for more information .

like image 24
android developer Avatar answered Sep 17 '22 15:09

android developer