栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android service 相关使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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文件中注册;

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/697129.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号