我有一個簡單的按鈕類,當按鈕被點擊時,我希望另一個類是instatiated和所有的方法調用。Android/Java類的範圍和上下文
public class SendClass extends BroadcastReceiver {
private static final int UDP_SERVER_PORT = 2562;
Context mContext ;
DatagramSocket mSocket ;
InetAddress myBcastIP, myLocalIP ;
@Override
public void onReceive(Context context, Intent intent) {
String msg = "Toast Message" ;
DatagramSocket ds = null;
mContext = context;
try {
ds = new DatagramSocket();
try {
myBcastIP = getBroadcastAddress();
mSocket = new DatagramSocket(UDP_SERVER_PORT);
mSocket.setBroadcast(true);
} catch (IOException e) {
}
String udpMsg = "hello";
InetAddress serverAddr = myBcastIP;
//InetAddress serverAddr = InetAddress.getByName("192.168.1.5");
DatagramPacket dp;
dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, UDP_SERVER_PORT);
ds.send(dp);
} catch (SocketException e) {
e.printStackTrace();
}catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
/**
* Calculate the broadcast IP we need to send the packet along.
*/
private InetAddress getBroadcastAddress() throws IOException {
WifiManager mWifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = mWifi.getConnectionInfo();
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
return null;
}
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads); // The high order byte is quads[0].
}
}
我認爲是與onReceive(Context context, Intent intent)
問題:Button類:
public class ButtonActivity extends Activity {
Button myButton;
TextView myLabel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton = (Button)findViewById(R.id.button1);
myLabel = (TextView)findViewById(R.id.textView1);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
myLabel.setText("Fired");
SendClass sendy = new SendClass();
sendy.onReceive(null, null);
}
});
}
}
第二類,其中發送廣播消息。
將ButtonClass中的值設置爲NULL
會導致關閉力,我不能讓它們明顯變爲空白。
使用代碼提示來設置他們:
sendy.onReceive(getBaseContext() , getIntent());
意味着敬酒行動火災,沒有FC,但絕不會在發送廣播消息。