Android Asynctask Example

Android Asynctask Example

In this tutorial we are going to see how to use Android AsyncTask. As we read from the Android Documentation :

  • AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
  • AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as ExecutorThreadPoolExecutor andFutureTask.
  • An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress andResult, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

在这个例子中我们将加载一个网页的背景和在WebView显示它。我们将注意到UI线程在其他UI活动仍然是快速响应。.

For this tutorial, we will use the following tools in a Windows 64-bit platform:

  • JDK 1.7
  • Eclipse 4.2 Juno
  • Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project. You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

create-project-attr

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

check-create-activity

Select “BlankActivity” and click Next.

create-blanc-activity

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

new-activity-attr

2. Create the main layout of the Application

Open res/layout/main.xml file :

main-xml

And paste the following code :

01<?xml version="1.0" encoding="utf-8"?>
02<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03    android:layout_width="match_parent"
04    android:layout_height="match_parent"
05    android:orientation="vertical" >
06 
07    <Button
08        android:id="@+id/btn"
09        android:layout_width="match_parent"
10        android:layout_height="wrap_content"
11        android:onClick="readWebpage"
12        android:text="Load Webpage" >
13    </Button>
14 
15    <Button
16        android:id="@+id/button1"
17        android:layout_width="match_parent"
18        android:layout_height="wrap_content"
19        android:onClick="dummyFunc"
20        android:text="Dummy Button" />
21 
22    <WebView
23        android:id="@+id/webView"
24        android:layout_width="fill_parent"
25        android:layout_height="fill_parent" />
26 
27</LinearLayout>

Now you may open the Graphical layout editor to preview the User Interface you created:

graphical-layout-editor

3. Code

Now we have to write the code of the application. Use the Package Explorer to navigate to the Java file of the Activity you’ve created:

main-src

The code of this tutorial is pretty much self explanatory.

01package com.javacodegeeks.android.androidasynctasktutorial;
02 
03import android.app.Activity;
04import android.content.Context;
05import android.os.AsyncTask;
06import android.os.Bundle;
07import android.view.View;
08import android.webkit.WebView;
09import android.widget.Toast;
10 
11public class MainActivity extends Activity {
12    final Context context = this;
13 
14    /** Called when the activity is first created. */
15 
16    @Override
17    public void onCreate(Bundle savedInstanceState) {
18 
19        super.onCreate(savedInstanceState);
20        setContentView(R.layout.main);
21 
22    }
23 
24    private class LoadWebPageASYNC extends AsyncTask<String, Void, String> {
25 
26        @Override
27        protected String doInBackground(String... urls) {
28 
29            WebView webView = (WebView) findViewById(R.id.webView);
30            webView.getSettings().setJavaScriptEnabled(true);
31            webView.loadUrl(urls[0]);
32 
33            return null;
34        }
35 
36        @Override
37        protected void onPostExecute(String result) {
38 
39        }
40    }
41 
42    public void dummyFunc(View view){
43        Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
44 
45    }
46 
47    public void readWebpage(View view) {
48        LoadWebPageASYNC task = new LoadWebPageASYNC();
49        task.execute(new String[] { "http://www.javacodegeeks.com" });
50 
51    }
52}

4. Run the application

This is the main screen of our Application:

main-screen

Now, when you press the “Load Webpage” button, the AsyncTask will start downloading and loading the Web Page. But, meanwhile if whe press the “Dummy Button”, you will see that the UI remains responsive. As you can see the web pages is loading and the UI is fast and responsive:

responsive

After a little while:

page-loaded

Download Eclipse Project

This was an Android Timer Example. Download the Eclipse Project of this tutorial: AndroidAsyncTaskTutorial.zip

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
毕业设计,基于SpringBoot+Vue+MySQL开发的公寓报修管理系统,源码+数据库+毕业论文+视频演示 现代经济快节奏发展以及不断完善升级的信息化技术,让传统数据信息的管理升级为软件存储,归纳,集中处理数据信息的管理方式。本公寓报修管理系统就是在这样的大环境下诞生,其可以帮助管理者在短时间内处理完毕庞大的数据信息,使用这种软件工具可以帮助管理人员提高事务处理效率,达到事半功倍的效果。此公寓报修管理系统利用当下成熟完善的Spring Boot框架,使用跨平台的可开发大型商业网站的Java语言,以及最受欢迎的RDBMS应用软件之一的MySQL数据库进行程序开发。公寓报修管理系统有管理员,住户,维修人员。管理员可以管理住户信息和维修人员信息,可以审核维修人员的请假信息,住户可以申请维修,可以对维修结果评价,维修人员负责住户提交的维修信息,也可以请假。公寓报修管理系统的开发根据操作人员需要设计的界面简洁美观,在功能模块布局上跟同类型网站保持一致,程序在实现基本要求功能时,也为数据信息面临的安全问题提供了一些实用的解决方案。可以说该程序在帮助管理者高效率地处理工作事务的同时,也实现了数据信息的整体化,规范化与自动化。 关键词:公寓报修管理系统;Spring Boot框架;MySQL;自动化;VUE
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值