2013-08-08 13 views
11

W mojej aplikacji mam aktywność i usługę ... Usługa będzie wysyłać wiadomości zebrane z danych z GPS ... Aktywność powinna otrzymywać wiadomości rozgłoszeniowe i aktualizować interfejs użytkownika ...Jak uzyskać dane z usługi do działania

mój kod

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); 
      } 
     } 
    } 
} 

Kiedy używam tego kodu nie działa prawidłowo ... używam ServiceReceiver klasy w osobnym pliku działa dobrze .... chcę ... !!

Odpowiedz

21

W moim klasy usługi Napisałem ten

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); 
} 

i na boku Aktywny musimy ten komunikat Broadcast

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
      mMessageReceiver, new IntentFilter("GPSLocationUpdates")); 

W ten sposób można wysyłać wiadomości do działania. tutaj mMessageReceiver jest klasa w tej klasie będzie odbywać co kiedykolwiek chcesz ....

w moim kodu zrobiłem tego ....

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(); 
    } 
}; 
+1

i nigdy nie zapomni wyrejestrować odbiornik wewnątrz OnPause –

+0

@FaisalNaseer Jak wyrejestrować możesz podać przykładowy kod, proszę –

+0

Po prostu 'unregisterReceiver (mMessageReceiver);' –

2

Istnieją trzy oczywistych sposobów na komunikację z usługami:

  1. Korzystanie z intencjami.
  2. Korzystanie z AIDL.
  3. Używanie samego obiektu usługi (jako singleton).
5

Dobry sposób na to, aby użyć Handler. Utwórz innerClass w swojej działalności, która rozszerza funkcję Handler i zastępuje metodę handleMessage.

Następnie w swojej klasie ServiceReceiver, utworzyć zmienną przewodnika i konstruktor takiego:

public ServiceReceiver(Handler handler){ 
    this.handler = handler; 
} 

Więc w swojej działalności, stworzyć swój własny program obsługi i przekazać go do serwisu. Tak więc, kiedy chcesz umieścić dane w swojej aktywności, możesz umieścić handler.sendMessage() w swojej usłudze (zadzwoni ona pod numer handleMessage twojej innerClass).

Powiązane problemy