在编写应用程序的时候,我们应当把硬盘、网络的IO操作等费时的任务放到其他线程完成。
2.3版本以后StrictMode可以帮助我们检查主线程中的这些操作并予以警告,但是通过JNI调用的方法它无法探测到。
当然如果环境在4.0以上,系统直接阻止这些费时的操作,会直接抛出android.os.NetworkOnMainThread Exception ,因此测试环境为2.3。
UI代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/image"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
/>
</LinearLayout>
在application的onCreated方法中启用 StrictMode。
application代码如下:
public class MyApplication extends Application {
private static MyApplication instance;
public static boolean DEVELOPER_MODE = true;
public static MyApplication getInstance() {
if (instance == null) {
instance = new MyApplication();
}
return instance;
}
public void onCreate() {
Log.d("Test", "SetStrictMode");
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
//.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate();
}
}
在activity中模拟了一个主线程下载图片。
activity代码如下:
public class MainActivity extends Activity {
private Bitmap bitmap = null;
private ImageView imageview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview = (ImageView) findViewById(R.id.image);
try {
bitmap = downloadImage("http://news.sciencenet.cn/upload/news/images/2011/3/20113301123128272.jpg");
} catch (IOException e) {
e.printStackTrace();
}
imageview.setImageBitmap(bitmap);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private Bitmap downloadImage(String urlStr) throws IOException {
HttpURLConnection conn = null;
InputStream inputStream = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
inputStream = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
return bitmap;
}
}
Log中的结果如图: