【发布时间】:2014-06-17 08:16:34
【问题描述】:
我有一个通过蓝牙接收消息的 Android 应用程序(但这部分与此处无关)。消息由处理程序接收。在被 Android 任务管理器杀死后启动应用程序时,它会正常工作。如果我不杀了它,只是把它带回前面,它的行为就不会像它应该的那样。代码很简单:
public class MainActivity extends Activity
{
private BtBase mBtBase;
private TextView mTvBluetooth;
private View mView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
mBtBase = BtBase.getInstance(this, mHandler);
setContentView(R.layout.bluetooth);
}
@Override
protected void onResume()
{
super.onResume();
mTvBluetooth = (TextView) findViewById(R.id.tvBluetooth);
if(mBtBase.getErrorCode() == BtLibraryConstants.BT_CONNECTED)
{
mTvBluetooth.setText("Text 1");
}
else
{
mTvBluetooth.setText("Text 2");
}
}
private final Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch(msg.what)
{
case 0:
if(msg.arg2 == 0)
{
Toast.makeText(getApplicationContext(), "Text 1", Toast.LENGTH_LONG).show();
mTvBluetooth.setText("Text 1.");
}
else if(msg.arg2 == 1)
{
Toast.makeText(getApplicationContext(), "Text 2", Toast.LENGTH_LONG).show();
mTvBluetooth.setText("Text 2");
}
break;
case 1:
Toast.makeText(getApplicationContext(), (String) msg.obj, Toast.LENGTH_LONG).show();
mTvBluetooth.setText("Text 3: " + (String) msg.obj);
break;
default:
}
}
};
}
从恢复情况启动应用程序后的工作原理:
- 处理程序中的 toast 消息正确显示
- onResume 中的文本视图根据状态具有正确的值
从恢复情况启动应用程序后什么不起作用:
- 处理程序中的文本视图更新不起作用。
请记住,toast 可以正常工作,因此代码会被执行。请记住,从任务管理器中杀死应用程序后它可以正常工作,因此它不是完全错误的。我认为它与生命周期管理有关。
我尝试了几件事
- 将主循环器传递给处理程序,但由于我是从主线程创建处理程序的,因此没有必要
- 获取主视图并在处理程序中将其无效以强制重绘
都没有奏效,但我当然可能在这些尝试中做错了什么。
调试器显示我的 textView mTvBluetooth 不为空,它看起来就是我要找的那个。但也许以某种方式创建了一个新的 mTvBluetooth,而我正在使用旧的 mTvBluetooth。
最后但并非最不重要的一点是 logCat 没有显示任何错误。
【问题讨论】:
-
蓝牙通信所需的对象。这需要我的处理程序发送消息。我认为这无关紧要,因为正在调用处理程序,吐司出现了。
-
检测到处理程序泄漏。此外,您可能应该确保 Handler 的 Looper 是主 Looper。
标签: android handler android-lifecycle onresume android-handler