Android service 相关使用

Android service 相关使用,第1张

Android service 相关使用 通过binder绑定连接,并与activity通讯; service代码
public class MyBinderService extends Service {

    private int count;

    private boolean quit=false;

    private Thread thread;

    private MyBinder myBinder=new MyBinder();

    public int getCount() {
        return count;
    }

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

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("tttttt","onBind service");

        return myBinder;
    }

    // 服务已运行,则不会调用此方法   在  onBind  onStartCommand  之前
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("tttttt","onCreate service");

        thread=new Thread(new Runnable() {
            @Override
            public void run() {
                while (!quit){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count++;
                }
            }
        });

        thread.start();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("tttttt","onStartCommand service");

        return super.onStartCommand(intent, flags, startId);
    }

    // 服务销毁时回调
    @Override
    public void onDestroy() {
        super.onDestroy();
        quit=true;
        Log.i("tttttt","onDestroy service");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.i("tttttt","onUnbind service");
        return super.onUnbind(intent);
    }
}

在activity使用:
    private ServiceConnection connection;
    private MyBinderService myBinderService;

 // 绑定
   bindService(new Intent(MainActivity2.this,MyBinderService.class),connection, Service.BIND_AUTO_CREATE);

         connection=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                MyBinderService.MyBinder myBinder= (MyBinderService.MyBinder) iBinder;
                myBinderService=myBinder.getService();
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                myBinderService=null;
            }
        };

// 获取数据
    if (myBinderService!=null){
       Log.i("tttttt",myBinderService.getCount()+"---get count---");
}

PS:记得在manifest文件中注册;

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5697266.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存