简体   繁体   English

Android / Java类的作用域和上下文

[英]Android / Java class scope and Context

I have a simple button class, that when the button is clicked , I wish another class to be instatiated and all the methods called. 我有一个简单的按钮类,当单击按钮时,希望另一个类被实例化,并调用所有方法。 Button class: 按钮类:

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 );       
          }
       });
     }  
   }

The second class, which sends a broadcast message: 第二类,发送广播消息:

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].
   }  

} }

The issue I think is with the onReceive(Context context, Intent intent) . 我认为问题在于onReceive(Context context, Intent intent)

Setting the values to NULL in the ButtonClass casues a force close, and I cannot leave them blank obviously. 在ButtonClass中将值设置为NULL会导致强制关闭,而我显然不能将它们留为空白。

Setting them using code hinting to: 使用代码提示将它们设置为:

sendy.onReceive(getBaseContext() , getIntent());

Means the Toast action fires, there is no FC , but the broadcast message is never sent. 表示将执行Toast操作,不存在FC,但从不发送广播消息。

使用getApplicationcontext()包含整个活动的信息。

getBaeContext获取应用程序上下文而不是活动上下文,您需要使用活动上下文

This is not correct way to send broadcast method, or activate broadcast receiver, you need to call: 这不是发送广播方法或激活广播接收器的正确方法,您需要致电:

Intent intent=new Intent(getApplicationContext(),SendClass.class);
sendBroadcast(intent);

As I mentioned ,the toast was firing ok, so I knew the method was being called ok. 正如我提到的那样,烤面包片烧得很好,所以我知道这种方法叫好。 Ill look into ApplicationContext now , but this particualar was a permissions one. 现在我会仔细研究ApplicationContext,但是这个特殊性是一种权限。

Adding 添加

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

To the manifest solved it. 到清单解决了。 Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM