JavascriptProva

Visualizzazione post con etichetta services. Mostra tutti i post
Visualizzazione post con etichetta services. Mostra tutti i post

martedì 5 aprile 2016

Un Service con un thread.

Adesso che ho un service, provo a fargli fare qualcosa, dopodiché si distrugge spontaneamente, secondo l'esempio che ho trovato in rete.

Eccolo:
public class Servizio extends Service{

 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }
 
 @Override
 public int onStartCommand(Intent intent,int flags, int startId){
  Log.v("SERVICE","PARTITO");
  new Thread (new Runnable(){

   @Override
   public void run() {
    for(int i=0;i<5;i++){
     try {
      Thread.sleep(1000);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
    stopSelf();
    
   }
   
  }).start();
  
  return Service.START_STICKY;
  
 }
 
 @Override
 public void onDestroy(){
  Log.v("SERVICE","DISTRUTTO");
 }

}


Meglio ancora questo con il contatore:
 @Override
 public int onStartCommand(Intent intent,int flags, int startId){
  Log.v("SERVICE","PARTITO");
  new Thread (new Runnable(){

   @Override
   public void run() {
    for(int i=0;i<5;i++){
     try {
      Thread.sleep(1000);
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
     Log.v("CONTATORE",""+i);
    }
    stopSelf();
    
   }
   
  }).start();
  
  return Service.START_STICKY;
  
 }
che dà un numero ogni secondo:
04-05 15:06:12.177: V/SERVICE(2323): PARTITO
04-05 15:06:13.185: V/CONTATORE(2323): 0
04-05 15:06:14.196: V/CONTATORE(2323): 1
04-05 15:06:15.206: V/CONTATORE(2323): 2
04-05 15:06:16.215: V/CONTATORE(2323): 3
04-05 15:06:17.226: V/CONTATORE(2323): 4
04-05 15:06:17.236: V/SERVICE(2323): DISTRUTTO

Services in Android

Che sono i services?
Mi esercito a creare un service.

Creo una nuova classe, e la chiamo "Servizio".
public class Servizio {

}
Estendo la classe Service:
public class Servizio extends Service{

}
Eclipse mi dà una segnalazione di errore dicendomi di aggiungere i metodi non implementati, che aggiungo:
public class Servizio extends Service{

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

}
(parallelamente a queste operazioni mi vengono importate le classi necessarie)

Se si tratta di un service "unbound", lascio che onBind continui a restituire null, e implemento altri metodi.

Ecco, ho implementato onStartCommand, con i parametri e tutto, come da tutorial.
Non ho idea, ancora, di cosa significhino i parametri flags e startId, e perché il valore restituito sia la costante START_STICKY. Vedremo in seguito...

public class Servizio extends Service{

 @Override
 public IBinder onBind(Intent intent) {
  // TODO Auto-generated method stub
  return null;
 }
 
 @Override
 public int onStartCommand(Intent intent,int flags, int startId){
  return Service.START_STICKY;
  
 }
}


Ci aggiungo un segnale alla partenza del Service, su LogCat:
 @Override
 public int onStartCommand(Intent intent,int flags, int startId){
  Log.v("SERVICE","PARTITO");
  return Service.START_STICKY;
  
 }
Adesso implemento il metodo onDestroy, quello che viene chiamato alla distruzione del Service:
 @Override
 public void onDestroy(){
  Log.v("SERVICE","DISTRUTTO");
 }
...con il relativo segnale in LogCat.
Ora con due Buttons accendo e spengo il Service, senza dimenticare però di segnalarlo anche in Manifest:
        </activity>
        <service android:name=".Servizio" />
    </application>
<uses-permission android:name="android.permission.BLUETOOTH" />
</manifest> 
Questo è il codice dell'Activity dalla quale manipolo il Service:
public class MainActivity extends Activity {
 
 Button button1;
 Button button2;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  button1=(Button)findViewById(R.id.button1);
  button2=(Button)findViewById(R.id.button2);
  
  View.OnClickListener onClickListener =new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    if(v==button1) IniziaService();
    if(v==button2) StopService();
    
   }
  };
  
  button1.setOnClickListener(onClickListener);
  button2.setOnClickListener(onClickListener);
  
 }
 
 public void IniziaService(){
  startService(new Intent(this,Servizio.class));
 }


 public void StopService(){
  stopService(new Intent(this,Servizio.class));
 }
 
}
E andiamo a vedere...

04-05 12:25:12.570: V/SERVICE(2226): PARTITO
04-05 12:25:17.742: V/SERVICE(2226): DISTRUTTO


Perfetto!!!