我正在编写一个Android应用程序,它具有受权限保护的广播接收器。接收来自经认证的应用程序的请求的广播接收器扫描硬编码IP地址的端口80。它返回套接字连接尝试的结果。在我的代码中,我有从OnReceive ( )
方法调用的套接字连接。我可以到达接收器,因为我可以看到吐司消息。但是,Exception E
捕获了套接字连接。这是接收器的代码:
package com.example.naveenbreceive;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class breceiver extends Activity {
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String Target="107.20.112.24";
int i=80;
int timeout=1000;
Toast.makeText(getApplicationContext(),"Intent Received",Toast.LENGTH_LONG).show();
Log.i("INFO","toast launched");
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(Target, i), timeout);
if (socket.isConnected())
{Toast.makeText(getApplicationContext(), "Connected to port 80", Toast.LENGTH_LONG).show();
socket.close();
}
else
{Toast.makeText(getApplicationContext(), "Unable to Connect port 80", Toast.LENGTH_LONG).show();
socket.close();
}
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"UnknownHost Exception",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"IO Exception",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"Exception",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
IntentFilter filterView = new IntentFilter();
filterView.addAction("com.example.HACKING");
registerReceiver(mReceiver, filterView,"com.example.permission.naveen", null);
Toast.makeText(getApplicationContext(),"Inside Receiver",Toast.LENGTH_LONG).show();
}
答案 0 :(得分:2)
广播接收器位于UI线程上。您无法在UI线程上进行联网。您需要在Thread或AsyncTask中执行此操作。
此外,BroadcastReceivers应该非常快,并且做的工作很少。他们的设计应该是一个快速通知,然后你在其他地方做繁重的工作,所以下一个应用程序可以得到通知。网络IO对接收器来说太过分了。