在android上运行在LAN上的UDP服务器

时间:2013-08-26 07:43:20

标签: java android multithreading service udp

我正在使用UDP服务器,但是我的服务器类给了我错误,我正在为我的服务器使用Service类并创建线程,但最终它没有运行并且给我错误,它在运行几秒后停止。

public class MainActivity extends Service {


static String UDP_BROADCAST = "UDPBroadcast";
DatagramSocket socket;


private void listenAndWaitAndThrowIntent(InetAddress broadcastIP, Integer port) throws Exception {
    byte[] recvBuf = new byte[15000];
    if (socket == null || socket.isClosed())
    {
        socket = new DatagramSocket(port, broadcastIP);
        socket.setBroadcast(true);
    }
    DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
    Log.e("UDP", "Waiting for UDP broadcast");
    socket.receive(packet);

    String senderIP = packet.getAddress().getHostAddress();
    String message = new String(packet.getData()).trim();
    Log.e("UDP", "Got UDB broadcast from " + senderIP + ", message: " + message);

//  broadcastIntent(senderIP, message);
    socket.close();
}
private void broadcastIntent(String senderIP, String message) {
    Intent intent = new Intent(MainActivity.UDP_BROADCAST);
    intent.putExtra("sender", senderIP);
    intent.putExtra("message", message);
    sendBroadcast(intent);
}
     Thread UDPBroadcastThread;

void startListenForUDPBroadcast() {
    UDPBroadcastThread = new Thread(new Runnable() {
        public void run() {
            try {
                InetAddress broadcastIP =     InetAddress.getByName("192.168.1.101"); //172.16.238.42 //192.168.1.255
                Integer port = 11111;
                while (shouldRestartSocketListen) {
                    listenAndWaitAndThrowIntent(broadcastIP, port);
                }
                //if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
            } catch (Exception e) {
                Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
            }
        }
    });
    UDPBroadcastThread.start();
}
           private Boolean shouldRestartSocketListen=true;

void stopListen() {
    shouldRestartSocketListen = false;
    socket.close();
}

@Override
public void onCreate() {

};

@Override
public void onDestroy() {
    stopListen();
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    shouldRestartSocketListen = true;
    startListenForUDPBroadcast();
    Log.i("UDP", "Service started");
    return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}
 }

我的日志猫是:

    08-26 19:28:44.232: D/AndroidRuntime(618): Shutting down VM
    08-26 19:28:44.252: W/dalvikvm(618): threadid=1: thread exiting with uncaught exception (group=0x409961f8)
    08-26 19:28:44.352: E/AndroidRuntime(618): FATAL EXCEPTION: main
    08-26 19:28:44.352: E/AndroidRuntime(618): java.lang.RuntimeException: Unable to   instantiate activity ComponentInfo{com.example.receiver/com.example.receiver.MainActivity}:   java.lang.ClassCastException: com.example.receiver.MainActivity cannot be cast to   android.app.Activity
    08-26 19:28:44.352: E/AndroidRuntime(618):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1879)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1980)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at android.app.ActivityThread.access$600(ActivityThread.java:122)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1146)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at android.os.Handler.dispatchMessage(Handler.java:99)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at android.os.Looper.loop(Looper.java:137)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at android.app.ActivityThread.main(ActivityThread.java:4340)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at java.lang.reflect.Method.invokeNative(Native Method)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at java.lang.reflect.Method.invoke(Method.java:511)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at dalvik.system.NativeStart.main(Native Method)
    08-26 19:28:44.352: E/AndroidRuntime(618): Caused by: java.lang.ClassCastException: com.example.receiver.MainActivity cannot be cast to android.app.Activity
    08-26 19:28:44.352: E/AndroidRuntime(618):  at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
    08-26 19:28:44.352: E/AndroidRuntime(618):  at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1870)
    08-26 19:28:44.352: E/AndroidRuntime(618):  ... 11 more

1 个答案:

答案 0 :(得分:0)

你正在混合你在这里尝试做的不同任务。您的活动必须延长Activity,以便Android能够在屏幕上显示它。另一方面,Service基本上是告诉Android您有一些背景或按需任务来处理的方法。

您需要从Activity中分离出您的用户界面(需要Service}。根据您的代码,您的类中实际上没有任何名为MainActivity的UI代码,因此您需要编写一个(扩展Activity)或将您的Intent指向现有的Activity你有。您还应重命名MainActivity,因为它实际上不是Activity

Android documentation for Service有一些可能有用的示例。