bindService使用BIND_AUTO_CREATE参数时服务未启动的问题
创始人
2024-12-18 03:00:17
0

需要在服务端的onBind方法中返回一个IBinder对象,同时在客户端中调用bindService方法时传入ServiceConnection对象,通过ServiceConnection的回调方法得到服务端返回的IBinder对象。以下是示例代码:

服务端代码:

public class MyService extends Service {
    private final IBinder binder = new MyBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class MyBinder extends Binder {
        public MyService getService() {
            return MyService.this;
        }
    }

    public int getRandomNumber() {
        return new Random().nextInt(100);
    }
}

客户端代码:

public class MainActivity extends AppCompatActivity {
    private MyService myService;
    private boolean isBound = false;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            MyService.MyBinder binder = (MyService.MyBinder) iBinder;
            myService = binder.getService();
            isBound = true;
            Log.d(TAG, "Service connected");
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            isBound = false;
            Log.d(TAG, "Service disconnected");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(this, MyService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(connection);
            isBound = false;
        }
    }

    public void onClick(View view) {
        if (isBound) {
            int number = myService.getRandomNumber();
            Toast.makeText(this, "Random number: " + number, Toast.LENGTH_SHORT).show();
        }
    }
}

相关内容

热门资讯

一分钟快速了解!Aapoker... 一分钟快速了解!Aapoker app,小程序雀神麻将来牌技巧,荔枝竞技有辅助吗(有挂细节);暗藏猫...
新手必备!菠萝德州偷偷看功能,... 新手必备!菠萝德州偷偷看功能,雀神小程序辅助app下载,多乐跑胡子是否有外挂(有挂细节)1、多乐跑胡...
技术分享!微扑克ai机器人打德... 技术分享!微扑克ai机器人打德州,广东雀神辅助器怎么买,快玩炸翻天大小牌怎么赢(有挂工具)1、在快玩...
热门推荐!gg扑克发牌问题,微... 热门推荐!gg扑克发牌问题,微信雀神广东麻将提高胜率技巧,友聚麻将有挂吗(有挂插件)友聚麻将有挂吗辅...
推荐十款!aapoker系统机... 推荐十款!aapoker系统机制,小程序雀神广东麻将辅牌器,潮汕暗宝真的能看穿吗(有挂规律)1、构建...
六分钟了解!微扑克智能辅助器,... 六分钟了解!微扑克智能辅助器,广东雀神游戏辅助神器,广西棋牌十三张有挂出千吗(有挂方法)1、点击下载...
总算清楚!微扑克大厅都是机器人... 总算清楚!微扑克大厅都是机器人,广东雀神外挂视频,人民棋牌可以调胜率吗(有挂黑科技)1、构建自己的人...
一分钟了解!wepoke辅助技... 一分钟了解!wepoke辅助技巧,微信小程序雀神广东麻将助赢神器,佛手在线机制(有挂规律)雀神广东麻...
终于清楚!aa扑克能用模拟器,... 终于清楚!aa扑克能用模拟器,微信雀神小程序控制台,欢乐达人辅助器(有挂攻略);1、欢乐达人辅助器透...
必备教程!gg扑克实战,全民雀... 必备教程!gg扑克实战,全民雀神怎么开挂,博雅红河棋牌有没有挂(有挂方法);1、博雅红河棋牌有没有挂...