java ui线程_java – 在Android中运行新线程和UI线程的方...

在Android应用中,UI线程负责界面的绘制和交互,避免重负载操作以保持界面响应性。可以使用AsyncTask在后台线程执行耗时任务,如验证用户凭证。当任务完成后,通过onPostExecute()方法在UI线程更新用户界面。
摘要由CSDN通过智能技术生成

UI线程和主线程只是同一线程的不同名称.

应用程序的所有UI通胀都在此主线程上完成.我们将“更重”的工作委托给其他线程的原因是因为我们不希望这些操作减慢UI的响应性和通胀时间.

您将需要运行任何更改UI的操作或修改主线程上UI使用的对象.

AsyncTask的一个例子

package com.wolfdev.warriormail;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.animation.Animation;

import android.view.animation.AnimationUtils;

import android.widget.Button;

import android.widget.CheckBox;

import android.widget.EditText;

public class LoginActivity extends Activity implements OnClickListener{

private Button loginButton;

private EditText eText;

private EditText pText;

private CheckBox box;

private String user;

private String pass;

@Override

public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.login);

//Initialize UI objects on main thread

loginButton = (Button) findViewById(R.id.button1);

loginButton.setOnClickListener(this);

eText = (EditText) findViewById(R.id.editText1);

pText = (EditText) findViewById(R.id.editText2);

eText.clearFocus();

pText.clearFocus();

Animation fadeIn = AnimationUtils.loadAnimation(this,R.anim.fadeanimation);

Animation slideIn = AnimationUtils.loadAnimation(this, R.anim.slideanimation);

eText.startAnimation(slideIn);

pText.startAnimation(slideIn);

box = (CheckBox)findViewById(R.id.checkBox1);

box.startAnimation(fadeIn);

login.startAnimation(fadeIn);

}

@Override

public void onClick(View v) {

user = email.getText().toString();

password = pass.getText().toString();

}

class LoginTask extends AsyncTask{

@Override

protected Void doInBackground(Void... args){

/* Here is where you would do a heavy operation

* In this case, I want to validate a users

* credentials. If I would do this on the main

* thread, it would freeze the UI. Also since

* this is networking, I am forced to do this on

* a different thread.

*/

return null;

}

@Override

protected void onPostExecute(Void result){

/* This function actually runs on the main

* thread, so here I notify the user if the

* login was successful or if it failed. If

* you want update the UI while in the background

* or from another thread completely, you need to

* use a handler.

*/

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值