将字符串从服务发送到 activity

Send string from service to activity

我正在尝试通过广播将字符串从服务发送到我的主 activity。 我在一些论坛上看到有两种使用广播的方法。一种是在清单中注册 activity,第二种方法是在本地的 activity 上注册。 我想知道如何使用第二种方式。我试过了,可惜没成功。

请告诉我哪里做错了。

服务代码

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

主要Activity代码

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


----------

嗯,我不知道我做错了什么,还有一个问题,我需要在

在设置动作中("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"?)

你可以做两件事:

1.你可以制作一个 class 并实现 Parcelable .
2. 使用 Intent 服务而不是服务 .

参考下面link: http://android-er.blogspot.in/2013/03/send-data-from-intentservice-to.html http://www.sanfoundry.com/java-android-program-send-data-service-activity/

LocalBroadcastManager 是解决此类问题的最佳解决方案。我已将 LocalBroadcastManager 实施到您现有的。这很容易。希望它会起作用。你的代码看起来像这样

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

}

private BroadcastReceiver broadcastReceiver = 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);
    LocalBroadcastManager.getInstance(MainActivity.this).registerReceiver(broadcastReceiver, new IntentFilter("NOW"));
  }

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

然后像这样从推送通知传递你的价值

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

您可以使用LocalBroadcastManager来实现您想要的。就像在您要发送数据时 service 调用此方法一样。

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

在你的Activity 在onCreate()

中注册一个Receiver
LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver, new IntentFilter("intentKey"));

并且出于 onCreate() 这个代码。

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