如何使用Android的返回值创建新线程

时间:2016-08-04 06:57:49

标签: android optimization thread-safety structure

我有一项活动,我需要根据互联网状态运行。问题是结构。我在 //其他代码中有很多行......

我想将它们放在onCreate()中,而不是在handleMessage()中。但我不知道该怎么做。

我正在寻找的结构:

need a new thread like below:
boolean xxxx() {
    judge internet;
    if internet is ok, return ok;
    else return bad;
}

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // codes...

    if (xxxx().equals("bad")) return;

    // other codes...

} 
}

我必须使用的结构:

Runnable newTread = new Runnable() {
@Override
public void run() {
    // judge net statements
    msg.obj = num;
    handler.sendMessage(msg);
}

};

Handler handler = new Handler() {

@Override
public void handleMessage(Message msg) {
    switch (msg.num) {
       case internet is ok: // other codes...
       case internet is bad: do nothing           
    }
} 
};

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // codes...

    Thread t= new Thread(newTread);
    t.start();

} 
}

0 个答案:

没有答案