6

Sto provando a creare un widget semplice con un pulsante che avvia uno Service con OnClickPendingIntent(). Posso iniziare bene, ma non riesco a capire un modo per fermarlo (so che posso farlo con un BroadcastReceiver o qualcosa di simile, ma vorrei evitare l'hardcode).PendingIntent per avviare e interrompere un servizio

Questo è il mio codice:

 Intent intent = new Intent(context, myService.class); 
     PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0); 

     RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget); 

     if (!ismyserviceup(context)) { 
      views.setOnClickPendingIntent(R.id.my_button, pendingIntent); 
     } else { 
      // i need to stop it!!!! 
     } 

risposta

17

Ci sono diversi modi per farlo, ecco uno:

Intent intent = new Intent(context, myService.class); 

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget); 

    if (ismyserviceup(context)) { 
     intent.setAction("STOP"); 
    } 
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);     
    views.setOnClickPendingIntent(R.id.my_button, pendingIntent); 

Poi sul servizio di onStartCommand(), è possibile controllare l'azione di intenti per "STOP" (probabilmente dovresti usare una stringa migliore) e chiamare stopSelf().

Problemi correlati