Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send string from service to activity

I'm trying to send string from service to my main activity with broadcast. I have read in a few forums that there are 2 ways to use broadcast. One is to register the activity in the manifest and the second way is to do it on the activity, local. I would like to know how I can use the second way. I have tried to do it but unfortunately I did not succeed.

Please tell me what I'm doing wrong.

Service code

   public class MyGcmListenerService extends GcmListenerService {

private static final String TAG = "MyGcmListenerService";

// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String typemessage = data.getString("typemessage"); // typeMessage = 0 or 1 = lock or unlock
    String datamessage = data.getString("datamessage"); // dataMessage = time and message that says lock or unlock

    Log.d(TAG, "TypeMessage: " + typemessage);
    Log.d(TAG,"DataMesaage:"+ datamessage);

    Intent in = new Intent();
    in.putExtra("TYPE",typemessage);
    in.setAction("NOW");
    sendBroadcast(in);
  ...

Main Activity Code

    public class MainActivity extends Activity implements SensorEventListener, Listen {

        private BroadcastReceiver statusReceiver;
        private IntentFilter mIntent;


    Sensor accelerometer;
    SensorManager sm;
    TextView acceleration;
    SendValues sv;
    int counter3 = 0;
    int counter5 = 0;

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         mIntent = new IntentFilter("NOW");

      // this.registerReceiver(,new IntentFilter("status"));

        sm = (SensorManager) getSystemService(SENSOR_SERVICE);
        sm.registerListener(this,accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
        accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        acceleration = (TextView) findViewById(R.id.sensorTxt);

        statusReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                String type = intent.getStringExtra("message");  //get the type of message from MyGcmListenerService 1 - lock or 0 -Unlock
                sm = (SensorManager) getSystemService(SENSOR_SERVICE);
                accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                Log.d(TAG, "Status: " + type);
                if (type == "1") // 1 == lock
                {
                    Toast.makeText(getApplication(), "Lock", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplication(), "UNLOCK", Toast.LENGTH_LONG).show();
                }
            }

        };
    }

        @Override
         protected void onResume()
         {
            super.onResume();
            registerReceiver(statusReceiver,mIntent);
          }

    @Override
    protected void onPause() {
        if(mIntent != null) {
            unregisterReceiver(statusReceiver);
            mIntent = null;
        }
        super.onPause();
    }


----------

Well I don't know what I'm doing wrong, and another question, what do I need to put in the

In set Action("I can put here any string/action that I what? And what does it mean action? I just want to send string to the main activity, what action should I do"?)

like image 777
Bolandian Eran Avatar asked May 19 '16 11:05

Bolandian Eran


People also ask

How to send data from service to activity?

So, in your activity, create your custom handler and pass it to your service. 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). Show activity on this post.

How to send message from service to activity in Android?

the mission : "Handle the Message in GeolocationService, and use the 'replyTo' property to send a new Message back to MainActivity with the latitude in 'arg1' and the longitude in 'arg2'. Then call setCoordinates(int lat, int long) from within MainActivity to update the coordinates."

How to start IntentService in Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view, when user gets the data from intent service it will update.

Which class is used to implement background services?

The IntentService class used to be the way for running an operation on a single background thread. IntentService runs outside the application in a background process, so the process would run even if your application is closed.


1 Answers

You can use LocalBroadcastManager to achieve what you want. Like in your service call this method when you want to send the data.

private static void sendMessageToActivity(String msg) {
  Intent intent = new Intent("intentKey");
  // You can also include some extra data.
  intent.putExtra("key", msg);
  LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

In your Activity register a Receiver in onCreate()

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

And out of onCreate() this code.

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
      // Get extra data included in the Intent
      String message = intent.getStringExtra("key");
      tvStatus.setText(message);
      // Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
  }
};
like image 134
Devendra Singh Avatar answered Sep 26 '22 05:09

Devendra Singh