将字符串从服务发送到活动

时间:2016-05-19 11:48:49

标签: android android-intent broadcastreceiver

我试图通过广播将字符串从服务发送到我的主要活动。 我在几个论坛上看到有两种方法可以使用广播。一个是在表演中注册活动,第二个方式是在活动中进行本地化。 我想知道如何使用第二种方式。我试图这样做但不幸的是我没有成功。

请告诉我我做错了什么。

服务代码

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

主要活动代码

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


----------

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

in.setAction("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"?)

3 个答案:

答案 0 :(得分:19)

当您想要发送数据时,您可以在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);
}

在您的活动中 在Receiver

中注册onCreate()
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();
}
};
希望你有个主意。

答案 1 :(得分:8)

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

答案 2 :(得分:2)

你可以做两件事:

<强> 1。你可以创建一个类并实现Parcelable 2.使用Intent服务而不是服务。

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

相关问题