Android中的线程示例

ram*_*ram 73 multithreading android

我想要一些关于线程创建和在android中调用线程的简单示例.

Rof*_*ion 86

这是一个很好的教程:

http://android-developers.blogspot.de/2009/05/painless-threading.html

或者这是UI线程:

http://developer.android.com/guide/faq/commontasks.html#threading

或者这里是一个非常实用的:

http://www.androidacademy.com/1-tutorials/43-hands-on/115-threading-with-android-part1

另一个关于procceses和线程

http://developer.android.com/guide/components/processes-and-threads.html

  • 前两个链接不起作用..对于第一个链接,请尝试[link](http://android-developers.blogspot.com/2009/05/painless-threading.html)对于第二个链接,请尝试[link] (http://developer.android.com/guide/components/processes-and-threads.html) (8认同)
  • 答案差不多是1.5岁.我尝试更新链接. (5认同)

小智 10

Androids强大的功能之一是AsyncTask类.

要使用它,您必须首先扩展它并覆盖doInBackground(...). doInBackground在工作线程自动执行,并且可以在UI线程添加一些听众收到通知的状态更新,这些功能被称为:onPreExecute(),onPostExecute()onProgressUpdate()

你可以在这里找到一个例子.

有关其他选择,请参阅以下帖子:

Handler vs AsyncTask vs Thread

  • 我刚刚更新了链接.该博客已移至这个新位置:[link](http://android-jotting.blogspot.com/2010/09/using-asynctasks-in-android.html) (2认同)

mbe*_*jda 8

这是Android的简单线程示例.这是非常基本的,但它应该帮助你获得一个观点.

Android代码 - Main.java

package test12.tt;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() { 
            public void run(){        
            txt1.setText("Thread!!");
            }
        }).start();

    }    
}
Run Code Online (Sandbox Code Playgroud)

Android应用程序xml - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
    android:id = "@+id/sm"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

  • 这似乎是一个不正确的例子,因为UI更新是从后台线程完成的. (48认同)
  • https://developer.android.com/guide/components/processes-and-threads.html完全不鼓励这种编程,因为它违反了"不要从UI线程外部访问Android UI工具包"规则 (2认同)