通过广播接收器发送数据无法在线程内创建处理程序

时间:2014-10-14 06:54:41

标签: android multithreading broadcastreceiver

我在Android中很新,所以请耐心等待我:)

我尝试通过广播接收器从Parser Activity向UI活动发送数据,我想在此处显示数据。

当我运行我的应用程序时,它会崩溃"无法在未调用Looper.prepare()"

的线程内创建处理程序

我把我的代码放在这里,所以你可以帮助我。

非常感谢 :)

      public class HandlePush extends Activity implements OnClickListener{

    Button mButton;
    TextView mSignal;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handlepush);

        mSignal=(TextView)findViewById(R.id.TodaySigTV);


        registerReceiver(myBroadCastReceiver, new IntentFilter("my.action.string"));

        mButton=(Button)findViewById(R.id.SignalButton);
        mButton.setOnClickListener(this);

        //Get a Tracker (should auto-report)
        ((AppManager) getApplication()).getTracker(AppManager.TrackerName.APP_TRACKER);
    }//oncreate



    private BroadcastReceiver myBroadCastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            Log.i("Receiver", "Broadcast received: " + action);
            if(action.equals("my.action.string")){
                String state = intent.getExtras().getString("extra");
                mSignal.setText(state);

            }
        }

    };


    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

        //Get an Analytics tracker to report app starts & uncaught exceptions etc.
        GoogleAnalytics.getInstance(this).reportActivityStart(this);
    }


    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();

        //Stop the analytics tracking
        GoogleAnalytics.getInstance(this).reportActivityStop(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = new Intent(getApplicationContext(), Contact.class);
        startActivity(intent);
        finish();
    }

}//handlepush


public class HistoryParser extends Activity{
// We don't use namespaces
        private final String ns = null;
        HistoryItems mObject;
        List<HistoryItems>mList;


        public List<HistoryItems> parse(InputStream inputStream) throws XmlPullParserException, IOException {
            try {
                XmlPullParser parser = Xml.newPullParser();
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                parser.setInput(inputStream, null);
                parser.nextTag();
                return readFeed(parser);
            } finally {
                inputStream.close();
            }
        }


        private List<HistoryItems> readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
            List<HistoryItems> entries = new ArrayList<HistoryItems>();

            parser.require(XmlPullParser.START_TAG, ns, "rss");
            while (parser.next() != XmlPullParser.END_DOCUMENT) {
                if (parser.getEventType() != XmlPullParser.START_TAG) {
                    continue;
                }
                String name = parser.getName();
                // Starts by looking for the entry tag
                if (name.equals("item")) {
                    entries.add(readEntry(parser));
                } else {
                    //                  skip(parser);
                }
            }  
            return entries;
        }


        private HistoryItems readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
            parser.require(XmlPullParser.START_TAG, ns, "item");
            String title = null;
            String dateStr = null;

            while (parser.next() != XmlPullParser.END_TAG) {
                if (parser.getEventType() != XmlPullParser.START_TAG) {
                    continue;
                }
                String name = parser.getName();
                if (name.equals("title")) {
                    title = readTitle(parser);
                //  sendData(title);////send the data from here
                } else if (name.equals("pubDate")) {
                    dateStr = readDate(parser);

                } else {
                    skip(parser);
                }
            } 
        //  sendData(title);////send the data from here
            return new HistoryItems(title, dateStr);

        }

        private String readTitle(XmlPullParser parser) throws XmlPullParserException, IOException {
            parser.require(XmlPullParser.START_TAG, ns, "title");
            String title = readText(parser);
            parser.require(XmlPullParser.END_TAG, ns, "title");
            sendData(title);////send the data from here
            return title;
        }

        private String readDate(XmlPullParser parser) throws XmlPullParserException, IOException{
            parser.require(XmlPullParser.START_TAG, ns, "pubDate");
            String date = readText(parser);
            parser.require(XmlPullParser.END_TAG, ns, "pubDate");
            return date;
        }

        // For the tags title and link, extract their text values.
        private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
            String result = "";
            if (parser.next() == XmlPullParser.TEXT) {
                result = parser.getText();
                parser.nextTag();
            }
            return result;
        }

        private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                throw new IllegalStateException();
            }
            int depth = 1;
            while (depth != 0) {
                switch (parser.next()) {
                case XmlPullParser.END_TAG:
                    depth--;
                    break;
                case XmlPullParser.START_TAG:
                    depth++;
                    break;
                }
            }
        }

        public void sendData(String title){

        Intent intent = new Intent("my.action.string");
        intent.putExtra("extra", title); // extra is the sent title
        sendBroadcast(intent);

        }

} // HistoryParser

10-14 11:23:10.297:E / AndroidRuntime(7674):致命异常:AsyncTask#1 10-14 11:23:10.297:E / AndroidRuntime(7674):java.lang.RuntimeException:执行doInBackground()时发生错误 10-14 11:23:10.297:E / AndroidRuntime(7674):在android.os.AsyncTask $ 3.done(AsyncTask.java:299) 10-14 11:23:10.297:E / AndroidRuntime(7674):at java.util.concurrent.FutureTask $ Sync.innerSetException(FutureTask.java:273) 10-14 11:23:10.297:E / AndroidRuntime(7674):at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 10-14 11:23:10.297:E / AndroidRuntime(7674):at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:307) 10-14 11:23:10.297:E / AndroidRuntime(7674):at java.util.concurrent.FutureTask.run(FutureTask.java:137) 10-14 11:23:10.297:E / AndroidRuntime(7674):在android.os.AsyncTask $ SerialExecutor $ 1.run(AsyncTask.java:230) 10-14 11:23:10.297:E / AndroidRuntime(7674):at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 10-14 11:23:10.297:E / AndroidRuntime(7674):at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:569) 10-14 11:23:10.297:E / AndroidRuntime(7674):at java.lang.Thread.run(Thread.java:856) 10-14 11:23:10.297:E / AndroidRuntime(7674):引起:java.lang.RuntimeException:无法在未调用Looper.prepare()的线程内创建处理程序 10-14 11:23:10.297:E / AndroidRuntime(7674):在android.os.Handler。(Handler.java:121) 10-14 11:23:10.297:E / AndroidRuntime(7674):在android.app.Activity。(Activity.java:749) 10-14 11:23:10.297:E / AndroidRuntime(7674):at com.Signals4Trading.push.android.HistoryParser。(HistoryParser.java:17) 10-14 11:23:10.297:E / AndroidRuntime(7674):at com.Signals4Trading.push.android.HistoryAct $ LongOperation.doInBackground(HistoryAct.java:64) 10-14 11:23:10.297:E / AndroidRuntime(7674):at com.Signals4Trading.push.android.HistoryAct $ LongOperation.doInBackground(HistoryAct.java:1) 10-14 11:23:10.297:E / AndroidRuntime(7674):在android.os.AsyncTask $ 2.call(AsyncTask.java:287) 10-14 11:23:10.297:E / AndroidRuntime(7674):at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:305) 10-14 11:23:10.297:E / AndroidRuntime(7674):... 5 more

1 个答案:

答案 0 :(得分:0)

你无法将广播接收器放在AsynTask中。 BroadCastReciver应该在活动中,在onCreate中你应该注册reiver和动作,如下所示:

registerreceiver(yourReceiver,new IntentFilter(yourAction));

希望它可以帮到你!!

编辑:

您应该在活动中(在AsynTask之外)声明您的广播接收器,就像属性一样。像这样:

private BroadcastReceiver myBroadCastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                String action = intent.getAction();
                Log.i("Receiver", "Broadcast received: " + action);
                if(action.equals("my.action.string")){
                    String state = intent.getExtras().getString("extra");
                    mSignal.setText(state);

                }
            }

        }