您的位置:首页 > 移动开发 > Android开发

Share some tips about android develop(一)

2013-05-14 22:36 561 查看
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.

@Override
public 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{
@Override
public 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{

@Override
public 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);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: