我在TI的OMAP4460处理器上使用Android 4.2。我的目标是这样,在启动后立即启动服务,以侦听多播套接字上的SSDP查询。我可以这样做,但是当我去创建MulticastSocket
时,我得到了一个例外。例外来自基础datagramSocket
。以下是一些代码段:
<receiver android:name="com.example.reciever.StartServicesAtBootReceiver" android:enabled="true" android:exported="false" android:label="StartServicesAtBootRemoteReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
我的onRecieve()
看起来像这样:
public void onReceive(Context context, Intent intent) {
Intent ServiceIntent = new Intent(context,
myService.class);
ComponentName serviceStarted = context
.startService(ServiceIntent);
if (serviceStarted != null)
}
最后,服务片段:
public int onStartCommand(Intent intent, int flags, int startId) {
try {
if (null == ssdpServer) {
ssdpServer = new UDPListenThread();
ssdpServer.start();
}
} catch (Exception e) {
e.printStackTrace();
}
public class UDPListenThread extends Thread {
protected MulticastSocket socket = null;
public UDPListenThread() throws IOException {
this("UDPListenThread");
}
public UDPListenThread(String name) throws IOException {
super(name);
}
@Override
public void run() {
Socket mySocket = new Socket();
socket = new MulticastSocket(SSDP_PORT);
// socket.setLoopbackMode(false);
socket.joinGroup(InetAddress.getByName(SSDP_ADDRESS));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
等
注意:Socket
确实被分配了(这里没有使用它,因此不确定它是否有效)。
另外,如果我尝试:
ConnectivityManager cm = (ConnectivityManager) getBaseContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
来自服务或接收方。 activeNetwork
以null
的形式返回。即使我等待activeNetwork
(来自服务)这样:
NetworkInfo activeNetwork = null;
while (null == activeNetwork) {
ConnectivityManager cm = (ConnectivityManager) getBaseContext()
.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
activeNetwork = cm.getActiveNetworkInfo();
Log.d(this.getClass().getSimpleName(), "activeNetwork "
+ activeNetwork);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
即使我能够启动浏览器并从用户界面搜索,它仍然为空。
跟进:原来这是一个糟糕的内核构建。我猜你是在垃圾堆上面建造的,你会得到一个不稳定的结构。 :)