I want to send a String from service to fragment with EventBus.
Here is the global EventBus :
public class Singleton {
private static EventBus eBus;
public static EventBus getEventBus() {
if (eBus == null)
eBus = EventBus.getDefault();
return eBus;
}
}
Here is the model class which I put String here :
public class Model {
public String mystring;
public void setMystring(String mystring) {
this.mystring = mystring;
}
public String getMystring() {
return mystring;
}
}
Here I send my String with EventBus from service :
public class Sample_Service extends Service {
Model model;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
model = new Model();
String action = intent.getAction();
if(action!=null) {
switch (action) {
case "send":
model.setName("Hello");
Singleton.getEventBus().postSticky(model);
break;
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
Inside subscribe method I receive the String correctly.
The problem is that outside this method my String is null.
In this fragment I receive the String :
public class Sample_Fragment extends Fragment {
public String mystring;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
service_intent.setAction("send");
ContextCompat.startForegroundService(context,service_intent);
// Here String is null when I want to show it on toast.
Toast.makeText(context,mystring,Toast.LENGTH_SHORT).show();
}
#Override
public void onStart() {
super.onStart();
//registering EventBus
Singleton.getEventBus().register(this);
}
#Override
public void onDestroyView() {
super.onDestroyView();
Singleton.getEventBus().unregister(this);
}
#Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void Get_Data (Model model) {
Model stickyEvent = EventBus.getDefault().getStickyEvent(Model.class);
mystring=model.get;
// Here I receive data successfully
Singleton.getEventBus().removeStickyEvent(stickyEvent);
}
}
What is a problem?
Related
I create an application with MVVM concept, there is fragment for viewpager in my Activity. some data changed when I change my language in my application, but the data that showed by webservices is not change. so I try to add android:configChanges="locale" in my every Activity and I already add this code on my Activity class :
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
recreate();
}
}
But its make my UI recreate every configuration change, including Screen Rotation while I just want to recreate if Language is changed.
this is my fragment code :
public class CatalogueFragment extends BaseFragment<FragmentCatalogueBinding, CatalogueViewModel>
implements CatalogueNavigator, CatalogueAdapter.CatalogueAdapterListener {
#Inject
CatalogueAdapter adapter;
#Inject
LinearLayoutManager mLayoutManager;
#Inject
ViewModelProvider.Factory factory;
FragmentCatalogueBinding fragmentCatalogueBinding;
private CatalogueViewModel catalogueViewModel;
public static CatalogueFragment newInstance(int Pos) {
Bundle args = new Bundle();
CatalogueFragment fragment = new CatalogueFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public int getBindingVariable() {
return BR.viewModel;
}
#Override
public int getLayoutId() {
return R.layout.fragment_catalogue;
}
#Override
public CatalogueViewModel getViewModel() {
catalogueViewModel = ViewModelProviders.of(this, factory).get(CatalogueViewModel.class);
return catalogueViewModel;
}
#Override
public void handleError(String error) {
// handle error
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
catalogueViewModel.setNavigator(this);
adapter.setListener(this);
}
#Override
public void onRetryClick() {
catalogueViewModel.fetchData();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
fragmentCatalogueBinding = getViewDataBinding();
setUp();
}
#Override
public void updateData(List<Movie> movieList) {
adapter.addItems(movieList);
}
private void setUp() {
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
fragmentCatalogueBinding.recyclerCatalogue.setLayoutManager(mLayoutManager);
fragmentCatalogueBinding.recyclerCatalogue.setItemAnimator(new DefaultItemAnimator());
fragmentCatalogueBinding.recyclerCatalogue.setAdapter(adapter);
}
}
and this is my ViewModel class
public class CatalogueViewModel extends BaseViewModel {
private final MutableLiveData<List<Movie>> movieListLiveData;
public CatalogueViewModel(DataManager dataManager, SchedulerProvider schedulerProvider) {
super(dataManager, schedulerProvider);
movieListLiveData = new MutableLiveData<>();
fetchData();
}
public void fetchData() {
setIsLoading(true);
getCompositeDisposable().add(getDataManager()
.getApiHelper().doMovieCall(URLConfig.API_KEY, getDataManager().getLanguage())
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(movieResponse -> {
if (movieResponse != null && movieResponse.getResults() != null) {
movieListLiveData.setValue(movieResponse.getResults());
}
setIsLoading(false);
}, throwable -> {
setIsLoading(false);
// getNavigator().handleError(throwable);
}));
}
public LiveData<List<Movie>> getMovieListLiveData() {
return movieListLiveData;
}
}
Can anybody show me where is my wrong? Thank you very much
You can use: ACTION_LOCALE_CHANGED
Here an example:
private BroadcastReceiver mLangReceiver = null;
protected BroadcastReceiver setupLangReceiver(){
if(mLangReceiver == null) {
mLangReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do what you want
}
};
registerReceiver(mLangReceiver, new IntentFilter(Intent.ACTION_LOCALE_CHANGED));
}
return mLangReceiver;
}
I'm trying using ReferenceQueue to check Activity if the activity is destory,Whether this activity is recycled.
I just using intent to Main2Activity.class:
switch (v.getId()){
case R.id.btn_turn_two:
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
break;
default:
break;
}
when I press to return MainActivity.class, the Main2Acitivity.class will be destroyed, so I using registerActivityLifecycleCallbacks watch activity in application,
public class MainApplication extends Application{
private watche watche;
#Override
public void onCreate() {
super.onCreate();
watche=new watche(this,getApplicationContext());
}
this class is check the Activity is destoryed.
public class watche {
KeyRefrence ref;
private Context context;
private final Set<String> retainedKeys = new CopyOnWriteArraySet<>();
private final ReferenceQueue<Object> referenceQueue=new ReferenceQueue<>();
public watche(Application application, Context context){
application.registerActivityLifecycleCallbacks(lifecycleCallbacks);
this.context=context;
}
Application.ActivityLifecycleCallbacks lifecycleCallbacks=new Application.ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
//weakrefrence to this activity
String key = UUID.randomUUID().toString();
retainedKeys.add(key);
final KeyRefrence weakReference=new KeyRefrence(activity,key,activity.getPackageName(),referenceQueue);
final MyAyTask myAyTask=new MyAyTask(weakReference,activity,context);
myAyTask.doInBackground(null);
}
};
public class MyAyTask extends AsyncTask {
private Activity activity;
private KeyRefrence keyRefrence;
private Context context;
public MyAyTask(KeyRefrence keyRefrence, Activity activity,Context context){
this.activity=activity;
this.context=context;
this.keyRefrence=keyRefrence;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
#Override
protected Object doInBackground(Object[] objects) {
gc();
ref=(KeyRefrence)referenceQueue.poll();
if (ref==null){
Log.d(TAG, "onActivityDestroyed:Acitivty is not destory");
}
else if (ref!=null){
Log.d(TAG, "doInBackground: "+ref);
}
return null;
}
}
I have create KeyReference implement WeakReference,and I didn't do anything in Main2Activity.class, I just press the phone return,I check the gc,is working ,but the referencequeue always empty, I'm sure the Activity is destoryed.
Good day, I have a fragment called MainFragment called from MainActivity. Inside MainFragment I have private OnProgressUpdateListener progressListener; this interface instance helps me talk to ProgressDialog Fragment.
I'm able to initialize interface instance inside my activities but I'm getting ClassCastException when I attempt to initialize the interface instance inside MainFragment
Below are my classes:
--------------------------------------------------------------------------------
Interface
--------------------------------------------------------------------------------
public interface OnProgressUpdateListener
{
void onProgressUpdate(String message);
void onDismissDialog();
}
--------------------------------------------------------------------------------
Child Fragment to MainFragment
--------------------------------------------------------------------------------
public class ProgressbarDialog extends DialogFragment implements OnProgressUpdateListener
{
TextView progressMessage;
ProgressBar progressBar;
View dialogView;
LayoutInflater inflater;
AlertDialog alertDialog;
AlertDialog.Builder dialogBuilder;
public ProgressbarDialog()
{
}
public static ProgressbarDialog newInstance(String title, String message)
{
ProgressbarDialog fragment = new ProgressbarDialog();
Bundle args = new Bundle();
args.putCharSequence("title", title);
args.putCharSequence("message", message);
fragment.setArguments(args);
return fragment;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
dialogBuilder = new AlertDialog.Builder(getActivity());
inflater = getActivity().getLayoutInflater();
dialogView = inflater.inflate(R.layout.content_progressdialog,null);
dialogBuilder.setView(dialogView);
progressBar = dialogView.findViewById(R.id.pbProgressSpinner);
progressMessage = dialogView.findViewById(R.id.tvProgressMessage);
dialogBuilder.setTitle(getArguments().getString("title"));
progressBar.setIndeterminate(true);
progressMessage.setText(getArguments().getString("message"));
alertDialog = dialogBuilder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
return alertDialog;
}
#Override
public void onProgressUpdate(String message)
{
progressMessage.setText(message);
}
#Override
public void onDismissDialog()
{
alertDialog.dismiss();
}
}
--------------------------------------------------------------------------------
MainFragment - Parent Fragment To ProgressbarDialog
--------------------------------------------------------------------------------
public class MainFragment extends Fragment
{
private View mainView;
private CheckBox rememberMe;
private boolean stayLoggedIn;
private CountDownLatch latch;
private FragmentManager manager;
private OnMainListener mListener;
private EditText email, password;
private ProgressbarDialog progressDialog;
private OnProgressUpdateListener progressListener;
private final int REGISTER_CODE = 1, RESET_CODE = 2;
private FloatingActionButton fabRegister, fabLogin, fabReset;
public MainFragment()
{}
public static MainFragment newInstance()
{
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getArguments() != null)
{}
manager = getChildFragmentManager();
progressDialog = ProgressbarDialog.newInstance("Authentication", "Connecting To Server, Please Wait...");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
mainView = inflater.inflate(R.layout.main_fragment, container, false);
stayLoggedIn = false;
rememberMe = mainView.findViewById(R.id.cbRememberMe);
email = mainView.findViewById(R.id.edtLoginEmail);
password = mainView.findViewById(R.id.edtLoginPassword);
fabRegister = mainView.findViewById(R.id.fabRegister);
fabLogin = mainView.findViewById(R.id.fabLogin);
fabReset = mainView.findViewById(R.id.fabReset);
return mainView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
email.setTag("Account Email Required!");
password.setTag("Account Password Required!");
}
#Override
public void onStart()
{
super.onStart();
rememberMe.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
stayLoggedIn = b;
}
});
fabRegister.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
mListener.onFABInteraction(REGISTER_CODE);
}
});
fabLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
onLoginRequest();
}
});
fabReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
mListener.onFABInteraction(RESET_CODE);
}
});
}
#Override
public void onAttach(Context context)
{
super.onAttach(context);
try
{
if (context instanceof OnMainListener)
{
mListener = (OnMainListener) context;
}
else
{
throw new RuntimeException(context.toString()
+ " must implement OnMainListener");
}
}
catch (Exception e)
{
Log.e(MainFragment.class.getName(), e.getMessage());
}
}
**#Override
public void onAttachFragment(Fragment childFragment) {
super.onAttachFragment(childFragment);
if(childFragment instanceof OnProgressUpdateListener)
{
progressListener = (OnProgressUpdateListener) childFragment;
//This code is never executed
}
}**
#Override
public void onDetach()
{
super.onDetach();
mListener = null;
}
interface OnMainListener
{
void onLoginSuccess(BackendlessUser user);
void onFABInteraction(int option);
}
private class OnAuthentication extends AsyncTask<String, String, BackendlessUser>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
latch = new CountDownLatch(1);
progressDialog.show(manager, MainFragment.class.getName());
Code Fails here, null pointer exception is thrown because progressListener interface instance is not initialised.
progressListener.onProgressUpdate("Authenticating User, Please Wait...");
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
progressListener.onProgressUpdate(values[0]);
}
#Override
protected BackendlessUser doInBackground(String... strings)
{
try
{
Backendless.UserService.login(
Utility.getText(email),
Utility.getText(password),
onLoginCallback, stayLoggedIn);
publishProgress("Validating Credentials, Please Wait...");
latch.await();
}
catch (InterruptedException e)
{
publishProgress(e.getMessage());
}
return Utility.loginUser;
}
#Override
protected void onPostExecute(BackendlessUser user)
{
super.onPostExecute(user);
Utility.clearViews(email, password, rememberMe);
progressListener.onDismissDialog();
if(user != null)
{
if(((MainActivity)getActivity()).onRoleValidation(user))
{
mListener.onLoginSuccess(user);
}
else
{
//send a push notification to master channel
Utility.sendNotification(getActivity(),
"New Application User",
"New Registration",
"New User Awaiting Role Assignment", "Master",
"Role Assignment Pending For User :"
+ user.getEmail()
+ ":" + user.getProperty("name").toString()
+ " " + user.getProperty("surname").toString());
}
}
}
}
private void onLoginRequest()
{
if(Utility.hasText(email, password))
{
if(Utility.isEmailValid(Utility.getText(email)))
{
new OnAuthentication().
execute(Utility.getText(email),
Utility.getText(password));
}
else
{
Utility.showToast(getActivity(), "Invalid Email");
Utility.clearViews(email);
}
}
}
private AsyncCallback<BackendlessUser> onLoginCallback = new AsyncCallback<BackendlessUser>()
{
#Override
public void handleResponse(BackendlessUser backendlessUser)
{
latch.countDown();
Utility.loginUser = backendlessUser;
Log.i(MainFragment.class.getName(), "Login Successful!\n" + backendlessUser.getUserId());
}
#Override
public void handleFault(BackendlessFault backendlessFault)
{
latch.countDown();
progressListener.onProgressUpdate("Login Unsuccessful!");
Log.e(MainFragment.class.getName(), "Login Failed!\n" + backendlessFault.getMessage());
}
};
}
I have a problem with code. I have two classes: MainActivity where i checking if sensor (in this case light sensor) is available and if yes - i try to get date from sensor from another class LightSensor, but result is always null. I think that i'm doing something wrong with listener but i don't know what.. and i'm sitting on this couple of hours and still nothing.. If you have any idea, please write and help me.
MainActivity class:
`public class MainActivity extends Activity implements EventListener {
SensorManager mSensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView wyswietl = (TextView)findViewById(R.id.res);
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
LightSensor mLightSensor = new LightSensor(getBaseContext());
if (mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) != null){
//mLightSensor.register();
String newLux = mLightSensor.getLux();
wyswietl.setText("Light level: " + newLux);
}
else{
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}`
and in MainActivioty class i don't know it argument in constructor :
LightSensor mLightSensor = new LightSensor(getBaseContext()); is good...
LightSensor class:
`public class LightSensor implements SensorEventListener {
public SensorManager mSensorManagerx;
public Sensor lightManager;
public String lux;
Context context;
public LightSensor(Context context){
//public void onCreateLight(Context context){
this.context = context;
mSensorManagerx = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManagerx.getDefaultSensor(Sensor.TYPE_LIGHT);
}
public void register(){
mSensorManagerx.registerListener(this, lightManager, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
lux = Float.toString(event.values[0]);
}
public String getLux(){
return lux;
}
public void unregister(){
mSensorManagerx.unregisterListener(this);
}
}`
You should not use a getter for this purpose, because the value your getting will be initialized after a unknown time. So it could still be null when you're calling the getLux method.
What you should do is use a listener pattern. I have changed your code a bit to give you an example implementation.
LightSensor:
public class LightSensor implements SensorEventListener {
public static interface LightSensorListener {
abstract void onLightSensorChanged(String lux);
}
private LightSensorListener listener;
private SensorManager mSensorManagerx;
private Sensor lightManager;
public LightSensor(Context context) {
mSensorManagerx = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManagerx.getDefaultSensor(Sensor.TYPE_LIGHT);
}
public void setListener(LightSensorListener listener) {
this.listener = listener;
}
public boolean register() {
return mSensorManagerx.registerListener(this, lightManager, SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
if (listener != null) {
listener.onLightSensorChanged(Float.toString(event.values[0]));
}
}
public void unregister() {
mSensorManagerx.unregisterListener(this);
}
}
Activity:
public class ActivityLightSensor extends Activity implements LightSensorListener {
private TextView text;
private LightSensor mLightSensor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView)findViewById(R.id.test);
mLightSensor = new LightSensor(getBaseContext());
mLightSensor.setListener(this);
}
#Override
public void onLightSensorChanged(String lux){
text.setText("Light level: " + lux);
}
#Override
protected void onResume() {
super.onStart();
if(!mLightSensor.register()){
Toast.makeText(this, "Light sensor not supported!", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
super.onStop();
mLightSensor.unregister();
}
}
onSensorChanged event is not called just after you created listener. It is called after something will change sensot value, then it will be called. So you should implement some callback, or, as for me, better would be to implement SensorEventListener in your activity, then just in onSensorChanged event method call
wyswietl.setText("Light level: " + newLux);
I am trying to make listener interface between two activities Act1 and Act2. Act1 will start Act2. If there is some event occurred in Act2, it will inform it to Act1. Problem is that I am starting new activity using Intent, so how Act1 will assign itself as listener to Act2's interface?
Act1.java
public class Act1 extends ActionBarActivity implements
ActionBar.OnNavigationListener {
ActionBar actionbar;
Intent pizzaIntent;
boolean visibleFirstTime = true;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menutab);
//set actionbar here
}
#Override
public boolean onNavigationItemSelected(int arg0, long arg1)// item pos,
// itemid
{
switch (arg0) {
case 0:
if(this.visibleFirstTime == false)
{
if(pizzaIntent == null)
{
pizzaIntent = new Intent(this,Act2.class);
//how to call setChangeListener?
}
startActivity(pizzaIntent);
}
else
this.visibleFirstTime = false;
break;
case 1:
System.out.println("selected: " + arg0);
break;
case 2:
System.out.println("selected: " + arg0);
break;
case 3:
System.out.println("selected: " + arg0);
break;
default:
break;
}
return true;
}
}
Act2.java
public class Act2 extends Activity {
selectionChangeListener listener;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pizza_slice_selection);
}
public void setChangeListener(selectionChangeListener listener)
{
this.listener = listener;
}
private interface selectionChangeListener
{
public void selectionMadeAtIndex(int index);
}
}
Note: Please don't suggest me to use fragments. I want to use activities currently.
I would suggest to create a model class. Let me give you an example:
Model class:
public class CustomModel {
public interface OnCustomStateListener {
void stateChanged();
}
private static CustomModel mInstance;
private OnCustomStateListener mListener;
private boolean mState;
private CustomModel() {}
public static CustomModel getInstance() {
if(mInstance == null) {
mInstance = new CustomModel();
}
return mInstance;
}
public void setListener(OnCustomStateListener listener) {
mListener = listener;
}
public void changeState(boolean state) {
if(mListener != null) {
mState = state;
notifyStateChange();
}
}
public boolean getState() {
return mState;
}
private void notifyStateChange() {
mListener.stateChanged();
}
}
And here's how you would use this:
// Imports
public class MainActivity extends Activity implements OnCustomStateListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomModel.getInstance().setListener(this);
boolean modelState = CustomModel.getInstance().getState();
Log.d(TAG, "Current state: " + String.valueOf(modelState));
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
#Override
public void stateChanged() {
boolean modelState = CustomModel.getInstance().getState();
Log.d(TAG, "MainActivity says: Model state changed: " +
String.valueOf(modelState));
}
}
Changing the member state in second activity:
// Imports
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CustomModel.getInstance().changeState(true);
}
}
LogCat output:
Current state: false
MainActivity says: Model state changed: true
Have you considered using LocalBroadcastManager?
In Act1's onCreate:
act2InitReceiver= new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// do your listener event stuff
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(act2InitReceiver, new IntentFilter("activity-2-initialized"));
In Act1's onDestroy:
LocalBroadcastManager.getInstance(this).unregisterReceiver(act2InitReceiver);
In Act2's onCreate:
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("activity-2-initialized"));
Give me a comment if the code doesn't compile, I'm writing it by hand.
The best, shortest and the easiest way to do this is to use static variables, like this:
class Main extends Activity {
static String message = "Hi";
}
class Another extends Activity {
public onCreate() {
Log.i(Main.message); // implementation of the message, 'Hi'
}
}