无法在没有调用looper prepare的线程内创建处理程序

时间:2012-09-02 04:31:12

标签: android loops handler

我是新手android程序员。刚开始看到一些在线教程,我决定为自己制作一个应用程序..直到昨天工作正常..我今天做的唯一改变就是添加这行“this.requestWindowFeature(Window.FEATURE_NO_TITLE);”它说抛出错误。请为此提供解决方案。

public class MainActivity extends Activity implements OnClickListener, Runnable {
Context context;

EditText editTextNum, editText, editUserName, editPassword;
Button btnsend;
ProgressDialog pd;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);     
    editUserName = (EditText) findViewById(R.id.edit_userName);
    editPassword = (EditText) findViewById(R.id.edit_password);
    editTextNum = (EditText) findViewById(R.id.edit_number);
    editText = (EditText) findViewById(R.id.edit_message);      
    btnsend = (Button) findViewById(R.id.btnsend);
    btnsend.setOnClickListener(this);
}

/** Called when the user clicks the Send button */
public void sendMessage() {
    if (!isOnline()) {
        Toast.makeText(MainActivity.this,"No Internet Access..Cannot Send SMS", Toast.LENGTH_LONG).show();
    } else {
        String userName = editUserName.getText().toString();
        String password = editPassword.getText().toString();
        String number = editTextNum.getText().toString();
        String message = editText.getText().toString();
        String msgreciever = number;
        String testMessage = message;
        try {
            SmsSender.sendMessage(msgreciever, testMessage, userName, password);
        } catch (Exception ex) {
            Toast.makeText(MainActivity.this, "SMS Sending Failed.",Toast.LENGTH_LONG).show();
        }

    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

public void onClick(View v) {
    // TODO Auto-generated method stub
    if (v == btnsend) {
        if (!isOnline()) {
            Toast.makeText(MainActivity.this,"No Internet Access..Cannot Send SMS",Toast.LENGTH_LONG).show();
        } else {
            pd = ProgressDialog.show(MainActivity.this, "Free Sms","Sending SMS..Please Wait..!!", true);
            Thread t = new Thread(this);
            t.start();
        }

    }
}

public void run() {
    // TODO Auto-generated method stub
    sendMessage();
    mHandler.sendEmptyMessage(0);
}

public Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        pd.dismiss();
        Toast.makeText(MainActivity.this, "Message Sent Successfully",Toast.LENGTH_LONG).show();
        editTextNum.setText("");
        editText.setText("");
        editTextNum.requestFocus();
    }
};
}

2 个答案:

答案 0 :(得分:4)

查看我的帖子,其中解释了这背后的原因:http://www.levinotik.com/2012/01/10/loopers-handlers-runtimeexceptions-explained/简而言之,您需要从一些线程中为Handler提供一个Looper。您可以通过执行new Handler(Looper.getMainLooper()):

来实现此目的

此外,您不应该在活动中管理自己的线程,或者至少不通常。你需要做的是创建我展示的Handler,然后调用mHandler.post(runnable),传入你想要运行的runnable。你不必要地创建一个新的Thread,这样你就可以调用start,这样就可以执行Runnable的run()方法了。为什么不让它直接运行,让处理程序发布为runnable?

所以看起来应该是这样的:

Handler mHandler = new Handler(Looper.getMainLooper());

Runnable myRunnable = new Runnable() {
 public void run() {work here...}
}

...elsewhere

mHandler.post(myRunnable);

事实上,如果你这样做,即使没有使用Looper.getMainLooper(),我也会感到惊讶;

修改

我不知道SmsSender是什么,但这可能是导致你找到新线程的原因。如果SmsSender正在做一些长期运行的工作,那么你应该做的是使用AsyncTask在后台完成这项工作。然后在onPostExecute中,您可以使用相关的whatevers更新您的UI。您似乎试图自己实现AsyncTask的功能,尽管没有成功。看看为什么?您正在尝试在后台执行一些昂贵的工作,然后使用Handler让UI更新状态。这正是AsyncTask旨在帮助您的,除了它正确地实现所有这些并使您更容易。 :)

答案 1 :(得分:0)

这对我有用,但我使用的是ProgressDialog。

myProgressDialog = ProgressDialog.show(MyActivity.this,
                getString(R.string.texto1) + "...",
                getString(R.string.texto2) + "...", true);
        myProgressDialog.getWindow().setType(
                WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
        new Thread( new Runnable() {     
            public void run() {     
                runOnUiThread(new Runnable(){
                    public void run() { 

                        Toast t = Toast.makeText(getApplicationContext(), "cadena a mostrar", Toast.LENGTH_SHORT);
                        t.show();

                    }


                });
                myProgressDialog.dismiss();
            }                         
        }).start();