Android Activity不使用BroadcastReceiver从IntentService接收消息

时间:2013-01-14 09:25:28

标签: android intentservice

我正在尝试开发一个Android应用程序来衡量网络的QoS。该应用程序将UDP数据包发送到我的系统上运行的UDP服务器。由于这是一个长时间运行的过程,我在扩展IntentService的类中实现了UDP连接。使用IntentService的原因是我需要将一些参数传递给Service。我的活动中有一个BroadcastReceiver,它侦听来自IntentService的消息并打印它。我的问题是虽然IntentService运行顺利,但活动没有收到来自它的消息。我是Android开发的新手,所以请原谅我缺乏理解,任何指导/建议都将深表感谢。我在下面发布我的代码的一些部分。 Logcat不会显示任何错误。 我已经看到在某些示例中使用了 intent.setAction()方法,但我不清楚如何在我的情况下使用它。

BroadcastReceiver(在我的Activity类中定义)

public class UdpResponseReceiver extends BroadcastReceiver {
 public static final String ACTION_RESP = "com.example.udpmessageclient.intent.action.MESSAGE_PROCESSED";
    @Override
    public void onReceive(Context context, Intent intent) {

        System.out.println(UdpService.PARAM_OUT_MSG);

    }

我已注册接收者:

IntentFilter filter = new IntentFilter(UdpResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new UdpResponseReceiver();
registerReceiver(receiver, filter);

IntentService类:

public class UdpService extends IntentService {

//..variable declarations

public UdpService() {
    // TODO Auto-generated constructor stub
    super("UdpService");
}

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    host = intent.getStringExtra("host");
    port = intent.getIntExtra("port", 4000);
    pType= intent.getIntExtra("pType", 0);
    delay = intent.getIntExtra("delay", 0);
    msg= intent.getStringExtra("msg");
    broadcastIntent = new Intent();
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 

    try {
        addr = InetAddress.getByName(host);
        // addr=InetAddress.getLocalHost();
        socket = new DatagramSocket();
        // socket.connect(addr,port);

        System.out.println("\nSocket Connected");
    } catch (Exception e) {
        System.out.println("\nConnection failed");
        return;
    }

    send=true;
    switch (pType) {
    case 0:
        while (send) {
            sendPacket(msg);
        }
    case 1:
        while (send) {
            try {
                Thread.currentThread().sleep(delay);
            } catch (Exception e) {
            }
            sendPacket(msg);
        }
    case 2:
        while (send) {
            int u = want(30);
            String data1 = "";
            while ((u--) > 0)
                data1 = data1 + msg;
            sendPacket(data1);
        }
    case 3:
        while (send) {
            int u = want(30);
            System.out.println(u);
            String data1 = "";
            while ((u--) > 0)
                data1 = data1 + msg;
            System.out.println("data length :" + data1.length());
            try {
                Thread.currentThread().sleep(delay);
            } catch (Exception e) {
            }
            sendPacket(data1);
        }

    }
}
public void onDestroy(){
    super.onDestroy();
    send=false;
    socket.close();
    socket=null;

}
void sendPacket(String text) {

    try {
        System.out.println("\nClient:: Sending packet: " + " to " + addr
                + port);
        byte[] data = text.getBytes();
        spacket = new DatagramPacket(data, data.length, addr, port);
        socket.send(spacket);
        String resultTxt="Sent Packet at:"+DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis());

// this is where I am trying to send message back to the activity

    broadcastIntent.putExtra(PARAM_OUT_MSG, resultTxt);
        sendBroadcast(broadcastIntent);
    } catch (Exception e) {
        System.out.println("Error:" + e.getMessage());
        e.printStackTrace();
        return;
    }
}

}

服务停止时

logcat错误消息:

01-14 15:53:41.446: W/System.err(1176): java.lang.NullPointerException
01-14 15:53:41.456: W/System.err(1176):     at com.example.udpmessageclient.UdpService.sendPacket(UdpService.java:123)
01-14 15:53:41.466: W/System.err(1176):     at com.example.udpmessageclient.UdpService.onHandleIntent(UdpService.java:74)
01-14 15:53:41.466: W/System.err(1176):     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
01-14 15:53:41.466: W/System.err(1176):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 15:53:41.466: W/System.err(1176):     at android.os.Looper.loop(Looper.java:137)
01-14 15:53:41.476: W/System.err(1176):     at android.os.HandlerThread.run(HandlerThread.java:60)

1 个答案:

答案 0 :(得分:2)

将UdpService的代码更改为...

broadcastIntent = new Intent(UdpResponseReceiver.ACTION_RESP); // You forgot to add your custom intent filter
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
//broadcastIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); // I don't think you really need it. So you can remove this flag. 

更新

public static final String ACTION_RESP = "com.example.udpmessageclient.intent.action.MESSAGE_PROCESSED";

private final BroadcastReceiver UdpResponseReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //TODO handle results

        }
    }; 

将其注册为

registerReceiver(UdpResponseReceiver, new IntentFilter(ACTION_RESP))