安卓:启动异步任务的onReceive方法 [英] Android: Start Async Task in OnReceive Method

查看:178
本文介绍了安卓:启动异步任务的onReceive方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有它管理的广播接收机的服务。此接收机可以被关闭和

目前收到短信时的onReceive被触发。然后将其上载的SMS到服务器。在code正常工作,但我从3.0听到上面的网络连接需要对异步任务运行。即使不是这种情况下,我想上载移动到另一个线程,因此上载任务不能阻止的UI线程。 (我已经累到服务移动到IntentService,这将导致广播接收器泄漏)

  SMSBR =新的广播接收器(){            @覆盖
            公共无效的onReceive(上下文的背景下,意图意图){
                // ONRECIVER的START ************************
                捆绑额外= intent.getExtras();                串strMessage =;                如果(临时演员!= NULL)
                {
                    [对象] smsextras =(对象[])extras.get(的PDU);                    的for(int i = 0; I< smsextras.length;我++)
                    {
                        SmsMessage smsmsg = SmsMessage.createFromPdu((字节[])smsextras [I]);                        。字符串strMsgBody = smsmsg.getMessageBody()的toString();
                        串strMsgSrc = smsmsg.getOriginatingAddress();                        strMessage + = + strMsgSrc +从短信:+ strMsgBody;                        Log.d(信息,为+ strMessage);
                        // ************ ***************
                        InputStream为= NULL;
                        尝试{
                            HttpClient的HttpClient的=新DefaultHttpClient();
                            HttpPost httppost =新HttpPost(http://mayar.abertay.ac.uk/~1001077/insert.php);                            ArrayList的<&的NameValuePair GT; namevaluepairs中=新的ArrayList<&的NameValuePair GT;();
                                nameValuePairs.add(新BasicNameValuePair(DeviceNumber,telephonyManager.getLine1Number()的toString())。);
                                nameValuePairs.add(新BasicNameValuePair(SenderNumber,strMsgSrc));
                                nameValuePairs.add(新BasicNameValuePair(信息,strMsgBody));
                                httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
                                HTT presponse响应= httpclient.execute(httppost);
                                HttpEntity实体= response.getEntity();
                                是= entity.getContent();
                                Log.d(是=,is.toString());
                                Log.d(在短信,发送成功);
                                  如果(Looper.getMainLooper()。getThread()== Thread.currentThread()){
                                        Log.d(关于UI消息上传暗战,);
                                    }其他{
                                        Log.d(关于UIX消息上传未运行,);
                                    }                        }赶上(例外五){
                            Log.e(Log_tag,在HTTP短信错误+ e.toString());
                            Log.d(在短信,发送不成功);
                        }
                        // ************ ****************                    }                }
                //在接收结束****************************
            }
          };


解决方案

让我来回答你的问题而不谈AsyncTasks:
看看


  

BroadcastReceiver.registerReceiver(广播接收器接收器,
  IntentFilter的过滤器,串broadcastPermission,处理器调度)


我发现,虽然我被检查的BroadcastReceivers一些文档,看起来像你需要什么(检查<一href=\"http://developer.android.com/reference/android/content/Context.html#registerReceiver%28android.content.BroadcastReceiver,%20android.content.IntentFilter,%20java.lang.String,%20android.os.Handler%29\"相对=nofollow称号=此链接>此链接)。还有一个提示:结合使用它 HandlerThread

I currently have a Service which manages a Broadcast Receiver. This receiver can be turned off and on.

At the moment the OnReceive is triggered when a SMS is received. It then uploads the SMS to a server. The code works fine, but I heard from 3.0 above network connections need to be ran on Async task. Even if this isn't the case I would like to move the upload to another thread, so the upload task can't block the UI thread. (I have tired to move the Service to an IntentService, this causes the broadcast Receiver leak)

          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****************************
            }


          };

解决方案

Let me answer your question without talking about AsyncTasks: Take a look at

BroadcastReceiver.registerReceiver (BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)

I found that while I was checking some documentation on BroadcastReceivers and looks like exactly what you need (check this link). One more hint: use it in combination with a HandlerThread.

这篇关于安卓:启动异步任务的onReceive方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆