Communication between activity and separate class - android

I have an Activity:
public class MyActivity extends Activity {
#Override
protected void onDestroy() {
// TODO: send event to other class
}
}
and a separate class:
public class MyClass{
MyClass(Context context){
// I have the context of activity
}
// This needs to be called by MyActivity in all other instantiates
void onActivityDestroy(){
}
}
MyClass is instantiated in other places and I want onActivityDestroy to be called in those instantiates. The place where MyClass is instantiated is not accessible.
I am looking for a solution that uses interfaces, listener, messages... but not static fields.

You can maintain the list of MyClass instances at application level then access that list in OnDestroy method of activity. And execute onActivityDestroy() version of each instance.
You should maintain list of instances in your Application class, whenever MyClass instance is created, you push that instance to the list maintained at Application Class
// this is to push the MyClass instance.
Context.getApplication().getMyClassInstanceList().add(new MyClass());
public class MyActivity extends Activity {
#Override
protected void onDestroy() {
List<Myclass> myClassObjects = Context.getApplication.getMyClassInstaceList();
for(Myclass myclass : myClassObjects)
{
myclass.onActivityDestroy();
}
}
}

Related

Using ActivityLifecycleCallbacks to reference current Activity

I would like to be able to receive a reference to the currently running activity from an arbitrary class (Utils, etc) without explicitly passing a reference.
I have considered something like this and would like some feedback about possible issues / alternatives.
public class MyApp extends Application implements ActivityLifeCycleCallbacks {
private Activity currentActivity;
public void onActivityResumed(Activity activity){
this.currentActivity = activity;
}
public void onActivityPaused(Activity activity){
if(this.currentActivity == activity)
this.currentActivity = null;
}
public Activity getCurrentActivity(){
return this.currentActivity;
}
}
Theoretically this should only hold a reference to the last resumed activity and allow other activities to be properly collected

Get & Set Value of my Activity from a fragment - Android

I would like know how can I get and set a value of my activity from my fragment?? is that possible?
below is my activity and the attribute 'myStation' is the value I want get and set from my fragment.
public class MyActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
public static Station myStation;
In my fragment I can execute 'getActivity()' but I really don't know if I can do that. if I'm wrong, what is the correct process?¿
Thanks.
If the fragment is only used in that activity, then you can simply cast the activity. Otherwise you'll have to verify that it is the correct activity perhaps using instance of.
Let's look at the simpler case:
public class MyActivity extends Activity {
private boolean myFlag;
public boolean getMyFlag() {
return myFlag;
}
public void setMyFlag(boolean myFlag) {
this.myFlag = myFlag;
}
And here would be the fragment to adjust the flag.
public class MyUniqueFragment extends Fragment {
public void updateActivityFlag(boolean myFlag) {
MyActivity myActivity = (MyActivity) getActivity();
myActivity.setMyFlag(myFlag);
}
}

Abstract class extend Thread

First question:
How can we use
ActivityManager activity =(ActivityManager)getSystemService(ForegroundApp.ACTIVITY_SERVICE)
And also
getPackageManager in a class that extends Thread?? I'm trying to fetch the Foreground activity's package name, its start time and end time in the foreground. I know this is Context based but I need to run this is in a thread.
Second Question:
How can we call an abstract class that extends thread in a service??
This thread only runs when the screen is ON. So, I'll be registering for Screen ON and OFF intents in a service. In this service, when the screen is on, i need to call this Thread.
Example:
abstract class A extends Thread {
abstract method met();
public void run() {
//Find out foreground's app name and its start and end time.
}
}
class B extends service {
//Here i need to call A.
}
All what you have to do is simply pass an reference to your Activity in first case to class A, and reference to class A to class B. Easiest way is to pass by constructor.
abstract class A extends Thread {
protected Activity activity;
public A(Activity activity) {
this.activity = activity;
}
abstract method met();
public void run() {
// activity.yourmethods()
//Find out foreground's app name and its start and end time.
}
}

send myObject (serializzable) from Activity to Fragment

Hy,
My activity must receive an object using sockets ..
This activity has within fragment A and fragment B.
I wish that every time the activity receiving the object, send it to fragment A.
how can I do?
I think this is a perfect example of where an event bus would be very handy. Check out Square's Otto. If you create an event bus and make it available to your activity and to your fragments (either via a static class or using dependency injection) you can send myObject via the bus without the need to serialize it.
Here's some example code. First I create a statically accessible global event bus in OttoBus.java. This is the bus on which we'll pass messages back and forth between the activity and the fragments. In the Activity I assume you'll have some kind of method that receives the data from the socket. The received data will be put in a SocketDataReceivedEvent object and sent on the bus. In your Fragment you register the fragment on the bus when the Fragment is started and unregister it when it's stopped (to avoid leaking). The Fragment must also have a method to handle the SocketDataReceivedEvent. This method can be named whatever you like as long as it's annotated with #Subscribe and takes a SocketDataReceivedEvent as it's only parameter.
---- OttoBus.java
import com.squareup.otto.Bus;
public class OttoBus {
private static Bus bus = new Bus();
public static void register(Object o) {
bus.register(o);
}
public static void post(Object data) {
bus.post(data);
}
public static void unregister(Object o) {
bus.unregister(o);
}
}
---- SocketDataReceivedEvent.java
public class SocketDataReceivedEvent {
public Object data;
public SocketDataReceivedEvent(Object data) {
this.data = data;
}
}
---- YourActivty.java
public class YourActivity extends Activity {
public void receiveSomethingOnSocket(Object theDataYouReceived) {
OttoBus.send(new SocketDataReceivedEvent(theDataYouReceived));
}
}
---- YourFragment.java
public class YourFragment extends Fragment {
#Override
public void onStart() {
super.onStart();
OttoBus.register(this);
}
#Override
public void onStop() {
super.onStop();
OttoBus.unregister(this);
}
#Subscribe
public void onSocketData(final SocketDataReceivedEvent e) {
// do something with e.data
}
}

Finishing an activity from a standard java class

I am currently working on an android project and I have an activity, lets call it MyActivity and this activity calls a standard Java class called MyClass.
I need MyClass to finish the MyActivity activity but I can't find out how to do this. I thought I might be able to pass the context to the standard java class and call context.finish() but this doesn't appear to be available.
How can I do this, thanks for any help you can offer.
You can pass the Context, but you will need to cast it to an Activity (or simply pass the Activity itself), although this in general seems like a bad practice.
The most secure solution uses listener and a Handler. It is complex, but ensures a non direct call to finish activity.
Your listener:
interface OnWantToCloseListener{
public void onWantToClose();
}
Class that should close activity.
class MyClass {
private OnWantToCloseListener listener;
public void setWantToCloseListener(OnWantToCloseListener listener){
this.listener = listener;
}
private void fireOnWantToClose(){
if(this.listener != null)
listener.onWantToClose();
}
}
When you want to close your activity you must call fireOnWantToClose() method.
public MyActivity extends Activity{
public void onCreate(){
final int CLOSE = 1; //number to identify what happens
MyClass my_class = new MyClass();
final Handler handler = new Handler(){
public void handleMessage(Message msg){
if(msg.what == CLOSE)
MyActivity.this.finish();
}
});
my_class.setOnWantToCloseListener(new OnWantToCloseListener(){
public void onWantToClose(){
handler.sendEmptyMessage(CLOSE);
}
});
}
}
This is secure because Activity is not finished directly by MyClass object, it is finished through a listener that orders a handler to finish activity. Even if you run MyClass object on a second thread this code will works nice.
EDIT: CLOSE var added I forget to declare and initialize this.
Pass the MyActivity to MyClass as an Activity. From there you can call myActivity.finish();
For example:
private Activity myActivity;
public MyClass(Activity myActivity){
this.myActivity = myActivity;
}
public void stopMyActivity(){
myActivity.finish();
}
And in MyActivity:
MyClass myClass = new MyClass(this);
This is risky, because you're holding a reference to an Activity, which can cause memory leaks.
If your java class is a nested inner class, you can use:
public class MyActivity extends Activity {
public static class JavaClass {
public void finishActivity() {
MyActivity.finish();
}
}
}
Otherwise you'll have to pass the java class a Context (i.e. pass it a reference to this, since Activity extends Context) and store it as a private instance variable.

Categories

Resources