美文网首页
[code]_[service]_[iBind:activity

[code]_[service]_[iBind:activity

作者: 勤学奋进小郎君 | 来源:发表于2018-08-23 01:21 被阅读0次

    Mainactivity.java

    public class MainActivity extends AppCompatActivity  implements View.OnClickListener{
    
        public myservice.download downloadbinder;
        private Button bt1;
        private Button bt2;
    
        private ServiceConnection conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                downloadbinder = (myservice.download)iBinder;
                downloadbinder.startdownload();
                downloadbinder.ondownload();
                downloadbinder.enddownload();
            }
    
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
            }
        };
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            bt1 = (Button)findViewById(R.id.button);
            bt1.setOnClickListener(this);
            bt2 = (Button)findViewById(R.id.button2);
            bt2.setOnClickListener(this);
        }
    
    
        @Override
        public void onClick(View view) {
                switch (view.getId()){
                    case R.id.button:
                        bindService(new Intent(MainActivity.this, myservice.class), conn, BIND_AUTO_CREATE);
                        break;
                    case R.id.button2:
                        unbindService(conn);
                }
            }
    
        }
    

    myservice.java

    public class myservice extends Service {
    
        private download binddownload = new download();
        class download extends Binder{
            public void startdownload() {
                Log.e("myservice", "start download");
            }
            public void ondownload(){
                Log.e("myservice", "download ....");
            }
            public void enddownload(){
                Log.e("myservice","end download");
            }
    
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return binddownload;
        }
    
        @Override
        public void onCreate(){
            super.onCreate();
            Log.e("myservice","create service");
        }
        @Override
        public void onDestroy(){
            Log.e("myservice","destroy service");
            super.onDestroy();
    
        }
    }
    

    结合文章[knowledgePoint]_[Service],来了解活动控制服务的操作

    相关文章

      网友评论

          本文标题:[code]_[service]_[iBind:activity

          本文链接:https://www.haomeiwen.com/subject/swguiftx.html