I am trying to send a string from a service to my main activity using translation. I read on several forums that there are 2 ways to use broadcast. one is to register activity in the manifest, and the second is to do it on activity locally. I would like to know how I can use the second method. I tried to do this, 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";
@Override
public void onMessageReceived(String from, Bundle data) {
String typemessage = data.getString("typemessage");
String datamessage = data.getString("datamessage");
Log.d(TAG, "TypeMessage: " + typemessage);
Log.d(TAG,"DataMesaage:"+ datamessage);
Intent in = new Intent();
in.putExtra("TYPE",typemessage);
in.setAction("NOW");
sendBroadcast(in);
Primary 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");
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");
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Log.d(TAG, "Status: " + type);
if (type == "1")
{
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 am doing wrong, and another question that I need to put in
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"?)
source
share