Service Download Service

Service category

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    public void down(String url){
        Log.e("######","执行");
        new MyThread(url).start();
    }

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

Download thread

class MyThread extends Thread{

    String url;

    public MyThread(String url) {
        this.url = url;
    }

    @Override
    public void run() {
        try {
            URL uu = new URL(url);
            HttpURLConnection hu = (HttpURLConnection) uu.openConnection();
            hu.connect();
            int cod = hu.getResponseCode();
            if(cod == 200){
                InputStream is = hu.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                EventBus.getDefault().postSticky(bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The main class

public class Demo extends AppCompatActivity {

    MyService.MyBinder binder;
    ImageView img;
    MyService services;
    Intent intent;
    String url = "http://img0.imgtn.bdimg.com/it/u=2025580240,2208429152&fm=26&gp=0.jpg";

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = ((MyService.MyBinder) service);
            services = binder.getservice();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

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

        img = findViewById(R.id.img);

        EventBus.getDefault().register(this);
    }

    public void down(View view) {
        services.down(url);
    }

    @Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
    public void gets(Bitmap bitmap){
        img.setImageBitmap(bitmap);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        

unbindService(connection);
    }
}

Renderings

Here Insert Picture Description


Guess you like

Origin blog.csdn.net/wangwei_weibo/article/details/90612228