在子线程中执行耗时的操作,避免阻塞主线程,从而调高运行效率
一、Thread
public class MainActivity extends AppCompatActivity {
private TextView tv_time;
private int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initThread();
}
private void initView() {
tv_time = findViewById(R.id.tv_time);
}
private void initThread() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
mHandler.sendEmptyMessage(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
mHandler.sendEmptyMessageDelayed(0, 2000);
new Thread(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
mHandler.sendEmptyMessage(0);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
tv_time.setText("ok");
}
});
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
@Override
public void run() {
tv_time.setText("yes");
}
}, 1000);
tv_time.post(new Runnable() {
@Override
public void run() {
tv_time.setText("case");
}
});
}
}).start();
}
private Handler mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
tv_time.setText("测试_" + (count++));
break;
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
}
}
二、AsyncTask
public class TestAsyncTask extends AsyncTask<String, Integer, byte[]> {
private Context mContext;
private ProgressDialog progressDialog;
private TextView tv_content;
public TestAsyncTask(Context mContext, TextView tv_content) {
this.mContext = mContext;
this.tv_content = tv_content;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(mContext);
progressDialog.setTitle("提示");
progressDialog.setMessage("正在加载数据...");
progressDialog.show();
}
@Override
protected byte[] doInBackground(String... params) {
try {
URL path = new URL(params[0]);
if (null != path) {
HttpURLConnection con = (HttpURLConnection) path.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(3000);
con.setDoOutput(true);
con.setDoInput(true);
con.connect();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = con.getInputStream();
ByteArrayOutputStream ops = new ByteArrayOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
if (inputStream != null) {
while ((len = inputStream.read(bytes)) != -1) {
ops.write(bytes, 0, len);
}
return ops.toByteArray();
}
}
}
} catch (Exception error) {
error.printStackTrace();
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
if (bytes == null) {
tv_content.setText("网络异常,加载数据失败!");
} else {
tv_content.setText(new String(bytes));
}
progressDialog.dismiss();
}
}
public class MainActivity extends AppCompatActivity {
private TextView tv_data;
private String url = "https://www.baidu.com/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_data = findViewById(R.id.tv_data);
new TestAsyncTask(this, tv_data).execute(url);
}
}
三 、IntentService
public class TestIntentService extends IntentService {
private static final String ACTION_FIRST = "com.example.first.action.First";
private static final String EXTRA_PARAM1 = "com.example.first.extra.PARAM1";
private static final String EXTRA_PARAM2 = "com.example.first.extra.PARAM2";
public TestIntentService() {
super("TestIntentService");
}
public static void startActionFirst(Context context, String param1, String param2) {
Intent intent = new Intent(context, TestIntentService.class);
intent.setAction(ACTION_FIRST);
intent.putExtra(EXTRA_PARAM1, param1);
intent.putExtra(EXTRA_PARAM2, param2);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
String action = intent.getAction();
if (ACTION_FIRST.equals(action)) {
String param1 = intent.getStringExtra(EXTRA_PARAM1);
String param2 = intent.getStringExtra(EXTRA_PARAM2);
handleActionFirst(param1, param2);
}
}
}
private void handleActionFirst(String param1, String param2) {
Log.d("aaa", param1 + param2);
}
}
四、HandlerThread
public class MainActivity extends AppCompatActivity {
HandlerThread mHandlerThread;
Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandlerThread = new HandlerThread("test");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 0:
Toast.makeText(MainActivity.this, "测试", Toast.LENGTH_SHORT).show();
break;
}
}
};
mHandler.sendEmptyMessage(0);
}
@Override
protected void onDestroy() {
super.onDestroy();
mHandler.removeCallbacksAndMessages(null);
mHandlerThread.quit();
}
}