0

I try send data from Service to Activity. I see that the Service starts and works, I also see that method sendMessageToActivity is called, but MapsActivity does not catch the message. I see My code:

GPS_Service.java

public class GPS_Service extends Service implements SensorEventListener{
  private Context mContext = this;
  @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        sendMessageToActivity("Coordinate");
    }
    ....
    private void sendMessageToActivity(String msg) {
        Intent intent = new Intent("GPSLocationUpdates");
        intent.putExtra("Status", msg);
        LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
        Log.i(TAG, "GPS_Service method was called);
    }
    ....
}

MapsActivity.java

public class MapsActivity extends FragmentActivity implements ... {
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
     @Override
     public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("Status");
        Log.i(TAG, "mMessageReceiver message:" + message);
     }
   };

  @Override
  protected void onCreate(Bundle savedInstanceState) { ...}
  @Override
  protected void onResume() {
    super.onResume();
    mAdView.resume();
    Log.i(TAG, "!!!onResume!!! ");
    LocalBroadcastManager.getInstance(this).registerReceiver(
            mMessageReceiver, new IntentFilter("GPSLocationUpdates"));
}

AndroidManifest.xml

...
<service android:name=".GPS_Service"
     android:process=":gps_service"
     android:stopWithTask="true"/>

<activity
     android:name=".MapsActivity"
     android:label="@string/title_activity_maps"
     android:theme="@style/SplashTheme">
     <intent-filter>
         <action android:name="android.intent.action.MAIN" />
         <category android:name="android.intent.category.LAUNCHER" />
     </intent-filter>
 </activity>
...
Roman
  • 1,045
  • 1
  • 12
  • 33
  • Have you tried my code? Let me know if there is an error – Kaushal28 May 12 '17 at 12:38
  • You can bind your GPS service to your map activity.Later you can use activity handler to push the data from service to activity. Flow this [link](https://stackoverflow.com/questions/8341667/bind-unbind-service-example-android) – Saurabh K. Sharma May 12 '17 at 12:21

1 Answers1

1

please declare service in manifest like as,

 <service android:name=".GPS_Service"/>

Remove the extra fields from it and test your application.

chetan mekha
  • 665
  • 6
  • 18