我目前有一个管理广播接收器的服务。可以关闭此接收器。
当收到短信时触发OnReceive。然后它将SMS上传到服务器。代码工作正常,但我从3.0上面听说网络连接需要在异步任务上运行。即使不是这种情况,我也想将上传移动到另一个线程,因此上传任务无法阻止UI线程。 (我已经厌倦了将服务移动到IntentService,这会导致广播Receiver泄漏)
SMSBR = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
//START OF ONRECIVER************************
Bundle extras = intent.getExtras();
String strMessage = "";
if ( extras != null )
{
Object[] smsextras = (Object[]) extras.get( "pdus" );
for ( int i = 0; i < smsextras.length; i++ )
{
SmsMessage smsmsg = SmsMessage.createFromPdu((byte[])smsextras[i]);
String strMsgBody = smsmsg.getMessageBody().toString();
String strMsgSrc = smsmsg.getOriginatingAddress();
strMessage += "SMS from " + strMsgSrc + " : " + strMsgBody;
Log.d("Message", "is "+strMessage);
//***************************************************************
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mayar.abertay.ac.uk/~1001077/insert.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("DeviceNumber", telephonyManager.getLine1Number().toString()));
nameValuePairs.add(new BasicNameValuePair("SenderNumber", strMsgSrc));
nameValuePairs.add(new BasicNameValuePair("Message", strMsgBody));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.d("is = ", is.toString());
Log.d("In SMS", "Sender success");
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
Log.d("Message upload Running", "on UI");
} else {
Log.d("Message upload NOT running", "on UIx");
}
}catch (Exception e){
Log.e("Log_tag", "Error in http sms " + e.toString());
Log.d("In SMS", "Sender NOT success");
}
//****************************************************************
}
}
//END OF ON RECEIVE****************************
}
};
答案 0 :(得分:1)
让我回答你的问题而不谈论AsyncTasks: 看看
BroadcastReceiver.registerReceiver(BroadcastReceiver接收器, IntentFilter过滤器,String broadcastPermission,Handler scheduler)
我发现当我检查BroadcastReceivers上的一些文档时,看起来就像你需要的那样(检查this link)。还有一个提示:将其与HandlerThread
结合使用。