Share some tips about android develop(一)

来源:互联网 发布:谷歌关键词优化 编辑:程序博客网 时间:2024/04/30 14:25

  Today I begin to write my blog!

  There are two reasons why I use English to write my blog: 1. To our IT guys, English is important for us, so I

recommand we should read and write English as much as possible; 2. My written English is really not so good, 

therefore I will grasp every chance to improve it. As my written English is poor,I will use the simplest words, for

this reason I give u my word that everyone will understand what I'm saying easilly.

    Let me list two issues about android development I metlast several days.

    1. When you share your data through "ContentProvider", if you wanna it work well on the version above 4.0,

remeber that you have to add android:exported="true" in <provider /> in manifest file.

    2. When u do some network operation which is time consuming, keep in mind that u should put it in a new thread rather than the main thread. If u put it in the main thread, it will cause NetworkOnMainThreadEcception if u use API above android4.0. U should do it like this,

   New a thread which u create for network operation in call back method, getimage from server in the LoadThread

instead of main thread, adn then send message to let handler to update UI in main thread.

@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.bt_load:LoadThread loadThread = new LoadThread();new Thread(loadThread).start();break;}}
private class MyHandler extends Handler{@Overridepublic void handleMessage(Message msg) {switch (msg.what) {case LOAD_IMAGE://Set the bitmap from server to UI.mImageView.setImageBitmap(bitmap);break;default:break;}}}public class LoadThread implements Runnable{@Overridepublic void run() {String address = mImageUrl.getText().toString().trim();if ("".equals(address)) {Toast.makeText(ImageLoadActivity.this, "Url is null", Toast.LENGTH_SHORT).show();return;}try {//Use address to get bitmap from server.bitmap = ImageLoadService.getImageBitmap(address);} catch (Exception e) {if (e instanceof IOException) {Toast.makeText(ImageLoadActivity.this, "IO exception", Toast.LENGTH_SHORT).show();} else if (e instanceof TimeoutException) {Toast.makeText(ImageLoadActivity.this, "Time out exception", Toast.LENGTH_SHORT).show();} else {Toast.makeText(ImageLoadActivity.this, "Unknown exception", Toast.LENGTH_SHORT).show();}e.printStackTrace();}//Notice handler to update UI interface in main thread.mHandler.sendEmptyMessage(LOAD_IMAGE);}}


原创粉丝点击