Cómo obtener datos del servicio a la actividad
En mi aplicación tengo una actividad y un servicio … El servicio de difusión de mensajes recogidos a partir de datos de GPS … La Actividad debe recibir los mensajes de difusión y actualizar la interfaz de usuario …
mi código
public class LocationPollerDemo extends Activity { private static final int PERIOD = 10000; // 30 minutes private PendingIntent pi = null; private AlarmManager mgr = null; private double lati; private double longi; private ServiceReceiver serviceReceiver; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mgr = (AlarmManager) getSystemService(ALARM_SERVICE); Intent i = new Intent(this, LocationPoller.class); i.putExtra(LocationPoller.EXTRA_INTENT, new Intent(this, ServiceReceiver.class)); i.putExtra(LocationPoller.EXTRA_PROVIDER, LocationManager.GPS_PROVIDER); pi = PendingIntent.getBroadcast(this, 0, i, 0); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi); DebugLog.logTrace("On Create Demo"); Toast.makeText(this, "Location polling every 30 minutes begun", Toast.LENGTH_LONG).show(); serviceReceiver = new ServiceReceiver(); IntentFilter filter = new IntentFilter("me"); this.registerReceiver(serviceReceiver, filter); } class ServiceReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { File log = new File(Environment.getExternalStorageDirectory(), "Location2.txt"); DebugLog.logTrace(Environment.getExternalStorageDirectory().getAbsolutePath()); try { BufferedWriter out = new BufferedWriter(new FileWriter(log.getAbsolutePath(), log.exists())); out.write(new Date().toString()); out.write(" : "); Bundle b = intent.getExtras(); Location loc = (Location) b.get(LocationPoller.EXTRA_LOCATION); String msg; if (loc == null) { loc = (Location) b.get(LocationPoller.EXTRA_LASTKNOWN); if (loc == null) { msg = intent.getStringExtra(LocationPoller.EXTRA_ERROR); } else { msg = "TIMEOUT, lastKnown=" + loc.toString(); } } else { msg = loc.toString(); } if (msg == null) { msg = "Invalid broadcast received!"; } out.write(msg); out.write("\n"); out.close(); } catch (IOException e) { Log.e(getClass().getName(), "Exception appending to log file", e); DebugLog.logException(e); } } } }
Cuando utilizo este código no está funcionando correctamente … Estoy usando la clase de ServiceReceiver en el archivo separado trabaja muy bien …. por favor dígame … !!
En mi clase de servicio escribí esto
private static void sendMessageToActivity(Location l, String msg) { Intent intent = new Intent("GPSLocationUpdates"); // You can also include some extra data. intent.putExtra("Status", msg); Bundle b = new Bundle(); b.putParcelable("Location", l); intent.putExtra("Location", b); LocalBroadcastManager.getInstance(context).sendBroadcast(intent); }
Y en el lado de la actividad tenemos que recibir este mensaje Broadcast
LocalBroadcastManager.getInstance(getActivity()).registerReceiver( mMessageReceiver, new IntentFilter("GPSLocationUpdates"));
De esta manera usted puede enviar el mensaje a una actividad. Aquí mMessageReceiver es la clase en esa clase que realizarás lo que quieras …
En mi código hice esto ….
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Get extra data included in the Intent String message = intent.getStringExtra("Status"); Bundle b = intent.getBundleExtra("Location"); lastKnownLoc = (Location) b.getParcelable("Location"); if (lastKnownLoc != null) { tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude())); tvLongitude .setText(String.valueOf(lastKnownLoc.getLongitude())); tvAccuracy.setText(String.valueOf(lastKnownLoc.getAccuracy())); tvTimestamp.setText((new Date(lastKnownLoc.getTime()) .toString())); tvProvider.setText(lastKnownLoc.getProvider()); } tvStatus.setText(message); // Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } };
Una buena manera de tenerlo es usar Handler. Cree un innerClass en su actividad que extienda Handler y handleMessage
método handleMessage
.
A continuación, en su clase ServiceReceiver
, cree una variable de controlador y un constructor como:
public ServiceReceiver(Handler handler){ this.handler = handler; }
Por lo tanto, en su actividad, cree su controlador personalizado y pasarlo a su servicio. Por lo tanto, cuando desea poner algunos datos a su actividad, puede poner handler.sendMessage()
en su servicio (se llamará handleMessage
de su innerClass).
Hay tres maneras obvias de comunicarse con los servicios:
- Usando Intenciones.
- Uso de AIDL.
- Uso del objeto de servicio en sí (como singleton).