标签:
*使用服务下载图片
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()); } }
标签:
原文地址:http://www.cnblogs.com/anni-qianqian/p/5390568.html