Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from service to activity

Tags:

android

In my app I have an activity and a service... The service will broadcast messages gathered from data from GPS... The Activity should receive the broadcast messages and update the UI...

my code

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

When I use this code it is not working properly... I am using ServiceReceiver class in separate file works fine.... please tell me...!!

like image 367
bGorle Avatar asked Aug 08 '13 11:08

bGorle


People also ask

How to send data to activity from intentservice?

So, when you wants to put some data to your activity, you can put handler.sendMessage () in your Service (it will call handleMessage of your innerClass). How to send data to Activity from IntentService ? You don't need to bind a service if the service is meant for one way communication.

How to pass data from activity to service in Android?

The following code shows how to Pass data from Activity To Service. Populate the MyService.java file with the following code: In the AndroidManifest.xml file, add the following statement: Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

How to pass a userid from activity to service?

So from an activity you will create the intent object to start service and then you place your data inside the intent object for example you want to pass a UserID from Activity to Service: Intent serviceIntent = new Intent (YourService.class.getName ()) serviceIntent.putExtra ("UserID", "123456"); context.startService (serviceIntent);

How to send data back from service to activity using result receiver?

In this sample, we will learn how to send data back from Service to Activity using Result Receiver: It is a generic interface for receiving a result from someone. Generate a random number in background using Intent Service and pass this number to Activity to be displayed. We will start a Intent Service from our Activity.


1 Answers

In my Service class I wrote this

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

and at the Activity side we have to receive this Broadcast message

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

By this way you can send message to an Activity. here mMessageReceiver is the class in that class you will perform what ever you want....

in my code I did this....

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();     } }; 
like image 155
bGorle Avatar answered Sep 28 '22 03:09

bGorle