简体   繁体   English

如何在Android的另一个线程中运行方法?

[英]How to run a method in another thread in Android?

I have a MainActivity class in Android that loads first screen. 我在Android中有一个MainActivity类,它会加载第一个屏幕。 When starting, I need to run another method in another thread and then either show message or go to another screen. 启动时,我需要在另一个线程中运行另一个方法,然后显示消息或转到另一个屏幕。 For UI not to hang. 对于UI不挂起。 How to do this? 这个怎么做? In which place of code? 代码在哪里?

// UPDATED CODE //更新的代码

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;

import android.view.Menu;
import android.widget.Toast;


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //Context context=getApplicationContext();
    String Internet=String.valueOf(isNetworkAvailable(this));
    Toast toast = Toast.makeText(this, Internet, Toast.LENGTH_SHORT);
    toast.show();
}

@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;
}

public static boolean isNetworkAvailable(Context context) 
{
    return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}

} }

You can go the Java route and utilize a normal Thread. 您可以走Java路线并利用普通的线程。 Note, however, that you will need a Handler (class located in the Android SDK) to propagate your changes to the UI. 但是请注意,您将需要一个Handler (位于Android SDK中的类)将您的更改传播到UI。
The more Android-kind-of way would be an AsyncTask . 更像Android的方式是AsyncTask It is designed specifically for tasks that have to run in parallel to the UI and provides a mechanism to call back to the UI, so you don't have to implement that yourself (exactly what you would do with the handler if you decide to choose the furst option). 它是专门为必须与UI并行运行的任务而设计的,并提供了一种回调UI的机制,因此您不必自己实现该功能(如果您决定选择,则对处理程序将执行的操作完全相同)。最远的选项)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM