Java-接口-如何在多个活动中共同分配特定接口

问题描述 投票:0回答:1

我有一个具有serviceinterface,我是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
java android interface callback
1个回答
0
投票
我为每个活动创建了不同的接口,并将它们注册到相应的活动中,并且它们起作用了!

MyApp.getInstance().setCallBackListener(this);

© www.soinside.com 2019 - 2024. All rights reserved.