如何在服务中使用主要活动中的相同对象

时间:2019-01-14 10:11:36

标签: android

我想从我的主活动中使用Service中的ArrayAdapter和MediaRouter对象。最好的解决方案是什么?

  public class MyActivity extends Activity {
    MediaRouter router;
    ArrayAdapter<RouteInfoWrapper> adapter;
    ListView list;

    MediaRouter.Callback callback = new MediaRouter.Callback() {
        @Override
        public void onRouteAdded(MediaRouter router, MediaRouter.RouteInfo route) {
            super.onRouteAdded(router, route);
            if (route.isDefault())
                return;
            adapter.add(new RouteInfoWrapper(route));
        }
    };

    public static class RouteInfoWrapper {
        MediaRouter.RouteInfo routeInfo;
        public RouteInfoWrapper(MediaRouter.RouteInfo routeInfo) {
            this.routeInfo = routeInfo;
        }

        @Override
        public String toString() {
            return routeInfo.getName();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        adapter = new ArrayAdapter<RouteInfoWrapper>(this, android.R.layout.select_dialog_item, android.R.id.text1);
        router = MediaRouter.getInstance(this);
        for (MediaRouter.RouteInfo route: router.getRoutes()) {
            if (route.isDefault())
                continue;
            adapter.add(new RouteInfoWrapper(route));

我要共享适配器,回调和路由器对象以供服务。

0 个答案:

没有答案