您的位置:首页 > 移动开发 > Android开发

java.lang.RuntimeException: 将消息发送到死的线程上处理程序的处理程序 (android.os.Handler)

2017-10-25 10:08 579 查看
在我的应用程序中我使用 IntentService 的发送短信。
@Override
protected void onHandleIntent(Intent intent) {
Bundle data = intent.getExtras();
String[] recipients = null;
String message = getString(R.string.unknown_event);
String name = getString(R.string.app_name);
if (data != null && data.containsKey(Constants.Services.RECIPIENTS)) {
recipients = data.getStringArray(Constants.Services.RECIPIENTS);
name = data.getString(Constants.Services.NAME);
message = data.getString(Constants.Services.MESSAGE);
for (int i = 0; i < recipients.length; i++) {
if(!StringUtils.isNullOrEmpty(recipients[i])) {
try {
Intent sendIntent = new Intent(this, SMSReceiver.class);
sendIntent.setAction(Constants.SMS.SEND_ACTION);
PendingIntent sendPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, sendIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent deliveryIntent = new Intent(this, SMSReceiver.class);
deliveryIntent.setAction(Constants.SMS.DELIVERED_ACTION);
PendingIntent deliveryPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, deliveryIntent, PendingIntent.FLAG_UPDATE_CURRENT);
SmsManager.getDefault().sendTextMessage(recipients[i].trim(), null, "[" + name + "] " + message, sendPendingIntent, deliveryPendingIntent);
} catch (Exception e) {
Log.e(TAG, "sendTextMessage", e);
e.printStackTrace();
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
MainActivity.instance.writeToLogFile(e.getMessage(), System.currentTimeMillis());
}
}
}
}
}
ecTransact(Binder.java:351)
W/MessageQueue(7180):   at dalvik.system.NativeStart.run(Native Method)
我的 SMSReceiver 位于另一个类。我怎样才能解决这个问题?

解决方法 1:

这里的问题是创建的 
Toast
 里面都由一个线程 
IntentService
 。该系统将使用 
Handler
 与此线程显示和隐藏关联 
Toast
 。第一次 
Toast
 将显示正确,但当系统试图隐藏它之后, 
onHandleIntent
 方法完成,因为将引发"将消息发送到死的线程上处理程序"的错误中至极的线程 
Toast
 创建的不再是有效的和 
Toast
 不会消失。若要避免此应显示 
Toast
 发布一条消息到主线程。下面是一个示例:
// create a handler to post messages to the main thread
Handler mHandler = new Handler(getMainLooper());
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐