使用新线程时的Android异常

时间:2015-01-04 10:16:18

标签: android multithreading exception

嗨,大家好我试图让应用程序通过Toast消息实时获取电池状态。因此,如果我插上电池充电器,它应该显示"电池正在充电",如果我拔下充电器,我应该显示"电池正在放电"等...对于这个我&#39 ; m使用新线程,但在运行时我的应用程序崩溃,我在logcat中得到错误

这里有我的代码和logcat:

public class MainActivity extends Activity {

Context cxt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bn = (Button) findViewById(R.id.button);
    cxt = this;


    Runnable myRunnable = new Runnable() {

        @Override
        public void run() {
            IntentFilter IF = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            Intent BatteryStatus = cxt.registerReceiver(null, IF);
            int status = BatteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
            boolean disCharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING;
            boolean usbCharge = status == BatteryManager.BATTERY_PLUGGED_USB;
            boolean acCharging = status == BatteryManager.BATTERY_PLUGGED_AC;

            if (isCharging) {
                Toast.makeText(getBaseContext(), "La batteria è in carica", Toast.LENGTH_SHORT).show();
            }
            if (disCharging) {
                Toast.makeText(getBaseContext(), "La batteria è in scarica", Toast.LENGTH_SHORT).show();
            }
            if (usbCharge) {
                Toast.makeText(getBaseContext(), "La batteria è in carica tramite USB", Toast.LENGTH_SHORT).show();
            }
            if (acCharging) {
                Toast.makeText(getBaseContext(), "La batteria è in carica tramite AC", Toast.LENGTH_SHORT).show();
            }
        }
    };

    Thread myThread = new Thread(myRunnable);
    myThread.start();

}

这是我在logcat中遇到的错误:

01-04 11:10:10.696    7706-7723/com.example.matteo.battery E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-4343
Process: com.example.matteo.battery, PID: 7706
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:200)
        at android.os.Handler.<init>(Handler.java:114)
        at android.widget.Toast$TN.<init>(Toast.java:336)
        at android.widget.Toast.<init>(Toast.java:100)
        at android.widget.Toast.makeText(Toast.java:250)
        at com.example.matteo.battery.MainActivity$1.run(MainActivity.java:43)
        at java.lang.Thread.run(Thread.java:818)

当我尝试启动新线程时,我认为我错了。

谢谢大家!

4 个答案:

答案 0 :(得分:4)

您无法在非UI线程中更新您的用户界面

您在Toast消息

中收到错误消息

如果您想在新线程中执行一些代码,并且在更新的UI之后可以使用AsyncTask,有关在新线程中更新ui的更多信息,您可以看到Update UI from Thread或查看Documentation

答案 1 :(得分:3)

试试这个

if (isCharging) {
    MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "La batteria è in carica", Toast.LENGTH_SHORT).show();
                }
            });
}

适用于所有Toast

不使用线程。创建BroadcastReceiver

BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
                boolean disCharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING;
                boolean usbCharge = status == BatteryManager.BATTERY_PLUGGED_USB;
                boolean acCharging = status == BatteryManager.BATTERY_PLUGGED_AC;
                //your code

            }
        };
        IntentFilter IF = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(receiver, IF);

BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Thread myThread = new Thread(myRunnable);
myThread.start();

            }
        };
        IntentFilter IF = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(receiver, IF);

答案 2 :(得分:1)

使用广播接收器可以更轻松地完成您尝试实现的结果。 看看以下official Documentation的android开发者网站。

答案 3 :(得分:1)

使用runOnUiThread在UI线程上运行指定的操作。

public class MainActivity extends Activity {

Context cxt;
Button bn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        bn = (Button) findViewById(R.id.button);
        cxt = this;


        Runnable myRunnable = new Runnable() {

            @Override
            public void run() {
                IntentFilter IF = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
                Intent BatteryStatus = cxt.registerReceiver(null, IF);
                int status = BatteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
                boolean disCharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING;
                boolean usbCharge = status == BatteryManager.BATTERY_PLUGGED_USB;
                boolean acCharging = status == BatteryManager.BATTERY_PLUGGED_AC;

                if (isCharging) {
                    showMessage("La batteria è in carica");
                }
                if (disCharging) {
                    showMessage("La batteria è in scarica");
                }
                if (usbCharge) {
                    showMessage("La batteria è in carica tramite USB");
                }
                if (acCharging) {
                    showMessage("La batteria è in carica tramite AC");
                }
            }
        };

        Thread myThread = new Thread(myRunnable);
        myThread.start();

    }

    private void showMessage(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getBaseContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }
}