0

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

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
4

1 回答 1

0

您在这里混合了您尝试执行的不同任务。您的活动必须扩展Activity,以便 Android 能够在屏幕上显示它。Service另一方面,它基本上是一种告诉 Android 你有一些后台或按需任务需要处理的方式。

您需要ActivityService. 根据您的代码,看起来您的类中实际上没有任何 UI 代码MainActivity,因此您需要编写一个(扩展Activity)或将您的 Intent 指向您现有Activity的。您还应该重命名MainActivity,因为它实际上不是Activity.

Android 文档Service有一些可能有用的示例。

于 2013-08-26T07:49:57.273 回答