码迷,mamicode.com
首页 > 其他好文 > 详细

Service服务

时间:2016-04-14 14:02:00      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

*使用服务下载图片

public class MainActivity extends AppCompatActivity {

    private Intent intent;
    public static Handler handle = new Handler() ;
    public static ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        intent = new Intent(this,MyService.class);
        imageView = (ImageView) findViewById(R.id.imageview);
        intent.putExtra("key","http://www.baidu.com/img/bdlogo.gif");
    }

    public void startService(View view){
        startService(intent);
    }

    public void stopService(View view){
        stopService(intent);
    }
}
public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("service","---onCreate"+Thread.currentThread());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("service","---onStartCommand"+Thread.currentThread());

        final String path = intent.getStringExtra("key");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    int code = connection.getResponseCode();
                    if(code == 200){
                        final Bitmap bitmap = BitmapFactory.decodeStream(connection.getInputStream());
                        MainActivity.handle.post(new Runnable() {
                            @Override
                            public void run() {
                                MainActivity.imageView.setImageBitmap(bitmap);;
                            }
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.i("service","---onStart"+Thread.currentThread());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("onDestroy","---onDestroy"+Thread.currentThread());
    }
}

 

Service服务

标签:

原文地址:http://www.cnblogs.com/anni-qianqian/p/5390568.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!