Content observer

Pour réagir à des changements système comme un changement dans la gestion des contacts du téléphone.

 Pour utiliser les « ContentObserver » vous devez réaliser deux étapes :
  • Implémenter une sous classe de ContentObserver,
  • Enregistrer votre content observer pour écouter les changements.

http://mylifewithandroid.blogspot.fr/2008/03/observing-content.html

Exemple d’implémentation dans un service :

ici on observe l’arrivée et le départ des sms 

 public class ServDelAllSms extends Service {  
   CallSmsObserver smsLogchangeevents = null;  
   @Override  
   public int onStartCommand(Intent intent, int flags, int startId) {  
     Log.d("SERVICE_OBSERVERSMS", "STARTED");  
     smsLogchangeevents = new CallSmsObserver(new Handler(),this);  
     getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true,  
         smsLogchangeevents);  
     //-- Inser Code here ----  
     ScanCallLog(this);  
     //---  
     return START_STICKY;  
   }  
   @Override  
   public void onDestroy() {  
     super.onDestroy();  
     //Unregister from call log change activities  
     this.getContentResolver().unregisterContentObserver(smsLogchangeevents);  
     Log.d("SERVICE_OBSERVERSMS", "STOPPED");  
   }  
   @Override  
   public IBinder onBind(Intent intent) {  
     // TODO Auto-generated method stub  
     return null;  
   }  
 class CallSmsObserver extends ContentObserver {  
   public CallSmsObserver(Handler handler, Context ct) {  
     super(handler);  
   }  
   @Override  
   public void onChange(boolean selfChange) {  
     Log.d("OBSERVER", "LOG SMS change");  
     //-- Laisse le temps au téléphone d'écrire dans le call log  
     new CountDownTimer(5000, 1000) { //-- tps compteur, interval pour message en millis  
       public void onFinish() {  
         ScanCallLog(ServDelAllSms.this);  
       }  
       public void onTick(long millisUntilFinished) {  
         // millisUntilFinished  The amount of time until finished.  
       }  
     }.start();  
     //super.onChange(selfChange);  
   }  
 }  

lancement du service :

startService(new Intent(this, ServDelAllSms.class));

Avec ajout dans le manifest de la déclaration du service et des permissions nécessaires 

<service android:name= ».ServDelAllSms » />

a) Implementation d’une sous classe de ContentObserver

ContentObserver is an abstract class with no abstract methods. Its twoonChange() methods are implemented without any logic. And since these are called whenever a change occurs, you have to override them.
Since Google added one of the two overloaded onChange() methods as recently as API-level 16, this method’s default behavior is to call the other, older method.
Here is, what a normal implementation would look like:

 class MyObserver extends ContentObserver {      
   public MyObserver(Handler handler) {  
    super(handler);        
   }  
   @Override  
   public void onChange(boolean selfChange) {  
    this.onChange(selfChange, null);  
   }      
   public void onChange(boolean selfChange, Uri uri) {  
    System.out.println("HMM");  
   }      
 }  
  • If you register an observer in onCreate you unregister in onDestroy
  • If you register an observer in onStart you unregister in onStop
  • If you register an observer in onResume you unregister in onPause

Le mieux est d’enregistrer l’observer dans un service puis de démarrer le service ou l’arrêter. Pour que le service se lance au boot, il est nécessaire d’enregistrer un BroadCastReceiver Onboot.

Nous aurons trois classes :

Une principale qui démarrera ou arrêtera le service

 bSwitch.setOnClickListener(new View.OnClickListener() {  
      @Override  
      public void onClick(View v) {  
                     if (!dpStatut)  
                          {SmsObservActivity.this.startService(sintent); //--start service SMS  
                           dpStatut=true;  
                           Toast.makeText( SmsObservActivity.this, "Service Actif", Toast.LENGTH_SHORT).show();   
                           bSwitch.setText("Service Actif");  
                           Log.d( LOG_TAG, "Activation du service !" );  
                           setPreferences();  
                          }  
                     else  
                       {SmsObservActivity.this.stopService(sintent);  //--stop service   
                        dpStatut=false;  
                        Toast.makeText( SmsObservActivity.this, "Service Inactif", Toast.LENGTH_SHORT).show();   
                        bSwitch.setText("Service Inactif");  
                        Log.d( LOG_TAG, "Désactivation du service !" );  
                        setPreferences();  
                       }}                  
               });       

 Une pour le service

http://www.vogella.com/tutorials/AndroidServices/article.html

Et une pour le broadcast qui démarrera le service si nécessaire au boot

 public class BootObserver extends BroadcastReceiver {   
   @Override  
   public void onReceive(Context context, Intent intent) {  
    SharedPreferences prefs = context.getSharedPreferences("androsmsobserver",   
          Context.MODE_PRIVATE);  
       boolean dpStatut = prefs.getBoolean("dpStatut",false);  
       if (dpStatut)  
       {Intent myIntent = new Intent(context, SmsService.class);  
     context.startService(myIntent);  
       }  
      }  
 }  

Le Manifest sera :

CaptureMnifBroadCast CaptureMnifService

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.andrologiciels.androsmsobserver"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
        <uses-permission android:name="android.permission.READ_SMS"/>
        <uses-permission android:name="android.permission.WRITE_SMS"/>
	<uses-permission android:name="android.permission.SEND_SMS"/>
	<uses-permission android:name="android.permission.RECEIVE_SMS"/>
	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.andrologiciels.androsmsobserver.SmsObservActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- Declaration du service de surveillance des SMS -->
        <service android:enabled="true" android:name="SmsService" />
        <!-- Declaration du broadcast receiver pour BOOT_COMPLETED event -->
        <receiver android:name=".BootObserver" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>
</manifest>

bbbb

Laisser un commentaire

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur la façon dont les données de vos commentaires sont traitées.

Articles récents
Commentaires récents
fatima dans Bienvenue !
AdminDroid dans Bienvenue !
fatima dans Bienvenue !
Archives
Catégories