I have a service
which has an interface
, I'm implementing
the interface callback
in multiple activities
, but because of I'm calling the app instance
on every activity's
onCreate
, the interfaces
are responding on the current activity
only. How do I make sure they work all together in every activity
.
MyApp.java
public class MyApp extends Application {
private static MyApp myApp;
@Override
public void onCreate() {
super.onCreate();
myApp = new MyApp();
}
@Contract(pure = true)
public static synchronized MyApp getInstance() {
MyApp myApp;
synchronized (MyApp.class) {
myApp = MyApp.myApp;
}
return myApp;
}
public void setCallBackListener(MyService.ReceiversCallbacks receiversCallbacks) {
MyService.receiversCallbacks = receiversCallbacks;
}
}
MyService.java
public class MyService extends Service {
public static MyService.ReceiversCallbacks receiversCallbacks;
public MyService() {
super();
}
public interface ReceiversCallbacks {
void onReceiveCallbacks(String data);
}
@Override
public void onCreate() {
super.onCreate();
Notification notification = new NotificationCompat.Builder(this, NOTIFICATION_ID)
.setContentTitle("Background service")
.setSmallIcon(R.drawable.ic_launcher)
.build();
startForeground(1, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (MY_LOGIC) receiversCallbacks.onReceiveCallbacks("DATA_FROM_MY_LOGIC");
//stopSelf();
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
ActivityA.java
public class ActivityA extends AppCompatActivity implements MyService.ReceiversCallbacks {
@Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.getInstance().setCallBackListener(this);
}
@Override
public void onReceiveCallbacks(String data) {
// calling important functions
}
}
ActivityB.java
public class ActivityB extends AppCompatActivity implements MyService.ReceiversCallbacks {
@Override
protected void onCreate(Bundle savedInstanceState) {
MyApp.getInstance().setCallBackListener(this);
}
@Override
public void onReceiveCallbacks(String data) {
// calling important functions
}
}
Each activity's onCreate
when I do this MyApp.getInstance().setCallBackListener(this);
The focus of the call back shifts to the new activity. But I want the focus in both or more activities at the same time, how do I do that? Is there any better way for the solution I want?
Please note these:
- I don't want to call those functions
onResume
- I don't want to use
Broadcasts