我有一个具有service
的interface
,我是implementing
在多个interface callback
中的activities
,但是因为我在每个instance
activity's
上调用应用程序onCreate
],interfaces
仅在当前activity
上响应。如何确保它们在每个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
}
}
执行此操作时每个活动的onCreate
MyApp.getInstance().setCallBackListener(this);
回调的重点转移到新活动上。但是我想同时关注两个或多个活动,该怎么做?有什么更好的方法可以解决我想要的问题吗?
请注意以下内容:
onResume
Broadcasts
MyApp.getInstance().setCallBackListener(this);