如何在处理程序中启动新的intent /调用方法?

时间:2013-05-20 06:06:25

标签: android android-intent handler

在我的情况下,如果来自蓝牙的strReceived与最终声明的字符串str匹配,我在启动新意图时会遇到问题或调用方法来启动此意图。如何解决'无法从类型Activity'对非静态方法getIntent()进行静态引用。

我注意到我无法在处理程序之外引用此全局strReceived值:

public class Standby extends ListActivity {

public final static String UUID = "00001101-0000-1000-8000-00805F9B34FB";
public final static String str = "\fDETECT1\n\r";
public static String strRead;
public static String strReceived;

BluetoothAdapter bluetoothAdapter;
BroadcastReceiver discoverDevicesReceiver;
BroadcastReceiver discoveryFinishedReceiver;

//---store all the discovered devices---
ArrayList<BluetoothDevice> discoveredDevices;
ArrayList<String> discoveredDevicesNames;

public static TextView txtData;

//---thread for connecting to the client socket---
ConnectToServerThread connectToServerThread;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.standby);

    //---init the ArrayList objects and bluetooth adapter---
    discoveredDevices = new ArrayList<BluetoothDevice>();
    discoveredDevicesNames = new ArrayList<String>();

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    //---for displaying the messages received---
    txtData = (TextView) findViewById(R.id.txtData);
}

//Method to make yourself discoverable
public void MakeDiscoverable(View view) 
{ 
    Intent i = new Intent(
        BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    i.putExtra(
        BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); //300 seconds
    startActivity(i);
}

//Method to discover other bluetooth devices
private void DiscoveringDevices() { 
    if (discoverDevicesReceiver == null) {
        discoverDevicesReceiver = new BroadcastReceiver() { 
            //Fired when a new device is discovered
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                //When a device is discovered---
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    //---get the BluetoothDevice object from 
                    // the Intent---
                    BluetoothDevice device = 
                        intent.getParcelableExtra(
                            BluetoothDevice.EXTRA_DEVICE);

                    //---add the name and address to an array 
                    // adapter to show in a ListView---
                    //---only add if the device is not already 
                    // in the list---
                    if (!discoveredDevices.contains(device)) {
                        //---add the device---
                        discoveredDevices.add(device);

                        //---add the name of the device; used for 
                        // ListView---
                        discoveredDevicesNames.add(device.getName());

                        //---display the items in the ListView---
                        setListAdapter(new 
                                ArrayAdapter<String>(getBaseContext(),
                                android.R.layout.simple_list_item_1, 
                                discoveredDevicesNames));
                    } 
                }
            }
        };
    }

    if (discoveryFinishedReceiver==null) {
        discoveryFinishedReceiver = new BroadcastReceiver() {
            //Fired when the discovery is done
            public void onReceive(Context context, Intent intent) {
                //---enable the listview when discovery is over; 
                // about 12 seconds---
                getListView().setEnabled(true); 
                Toast.makeText(getBaseContext(), 
                        "Discovery completed. Please select BlueBee.", 
                        Toast.LENGTH_LONG).show();
                unregisterReceiver(discoveryFinishedReceiver);
            } 
        };
    }

    //---register the broadcast receivers---
    IntentFilter filter1 = new
        IntentFilter(BluetoothDevice.ACTION_FOUND);
    IntentFilter filter2 = new
        IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

    registerReceiver(discoverDevicesReceiver, filter1);
    registerReceiver(discoveryFinishedReceiver, filter2);

    //---disable the listview when discover is in progress---
    getListView().setEnabled(false);
    Toast.makeText(getBaseContext(), 
            "Discovery in progress...please wait...", 
            Toast.LENGTH_LONG).show();
    bluetoothAdapter.startDiscovery();
}


//Calls the method to discover other bluetooth devices
public void DiscoverDevices(View view) 
{
    //---discover other devices---
    DiscoveringDevices();   
}

static Handler UIupdater = new Handler(){
public void handleMessage(Message msg) { 
    int numOfBytesReceived = msg.arg1;
    byte[] buffer = (byte[]) msg.obj;
    //---convert the entire byte array to string---
    String strReceived = new String(buffer);
    //---extract only the actual string received---
    strReceived = strReceived.substring(
        0, numOfBytesReceived);

    //---display the text from string str on the TextView in one line only---
    //txtData.setText(strReceived);

    //Compare string. Method will return 0 if both are identical
    if (strReceived.compareTo(str)==0){
        txtData.setText("FALL DETECTED!!");
        Intent i = new Intent ("com.example.NEXT"); 

        //Get the data using bundle
        //Add the set of extended data to the intent and start it
        Bundle b = getIntent().getExtras(); 
        i.putExtras(b);
        startActivity(i);
        //readySMS();
    }
}
};

//Fired when method is called
public void readySMS() {

    // TODO Auto-generated method stub
        Intent i = new Intent ("com.example.NEXT"); 

        //Get the data using bundle
        //Add the set of extended data to the intent and start it
        Bundle b = getIntent().getExtras(); 
        i.putExtras(b);
        startActivity(i);
}

public void onPause() {
    super.onPause();
    //---cancel discovery of other bluetooth devices
    bluetoothAdapter.cancelDiscovery();

    //---unregister the broadcast receiver for 
    // discovering devices--- 
    if (discoverDevicesReceiver != null) {
        try {
            unregisterReceiver(discoverDevicesReceiver); 
        } catch(Exception e) {
        }
    }

    //---if you are currently connected to someone...---
    if (connectToServerThread!=null) { 
        try {
            //---close the connection---
            connectToServerThread.bluetoothSocket.close();

            //Calls the method to get ready to SMS
        } catch (IOException e) {
            Log.d("MainActivity", e.getLocalizedMessage());
        }
    }
}

//Fired when a client is tapped in the ListView---
public void onListItemClick(ListView parent, View v, 
int position, long id) {
    //---if you are already talking to someone...---
    if (connectToServerThread!=null) {
        try {
            //---close the connection first---
            connectToServerThread.bluetoothSocket.close();
        } catch (IOException e) {
            Log.d("MainActivity", e.getLocalizedMessage());
            //Toast.makeText(this, "Connect failed", Toast.LENGTH_SHORT).show();
        }
    }

    //---connect to the selected Bluetooth device---
    BluetoothDevice deviceSelected =
        discoveredDevices.get(position); 
    connectToServerThread = new 
        ConnectToServerThread(deviceSelected, bluetoothAdapter);
    connectToServerThread.start();

    /*  
    Thread cancel = new Thread(){   
            public void run(){
                    //this must be the same as the action name to be performed in manifest.xml file
                    //if (txtData.getText().toString().equalsIgnoreCase(str)){

                    //if (strReceived!=null){
                    //  strRead = strReceived;
                    //  if (strRead.compareTo(str)==0){
                            try{
                                sleep(3000);
                                Intent i = new Intent ("com.nick.falldetection.CANCEL");    

                                //Get the data using bundle
                                //Add the set of extended data to the intent and start it
                                Bundle b = getIntent().getExtras(); 
                                //String owner = b.getString("abc");
                                //String message = b.getString("longMessage");
                                //String phoneNo = b.getString("phoneNo");    

                                i.putExtras(b);
                                startActivity(i);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                            finally{
                                //finish();
                            }
                        }
                    //}
    };

                    {
    cancel.start();

}
*/

};
}

2 个答案:

答案 0 :(得分:0)

您可以通过在YourActivity mActivity中添加Handler字段并在活动this中将其设置为onCreate来解决此问题。这样,您就可以通过YourActivity从处理程序中获取mHandler.mActivity.yourFieldOrMethod所拥有的任何内容。

你喜欢这个

class MyActivity {

static class MyHandler extends Handler() {
   MyActivity mActivity;
   void handleMessage() { 
        mActivity.someMethod();
   }
};

private MyHandler uiHandler = new MyActivity();

private void someMethod() { /* ... */ }

void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);
    uiHandler.mActivity = this;
}

}

答案 1 :(得分:0)

试试这个。

 Standby me;
 protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
me = this;
}
static Handler UIupdater = new Handler()
  {
 public void handleMessage(Message msg) 
  { 

strReceived = me.strReceived.substring(0, numOfBytesReceived);

抱歉延误。希望这会对你有所帮助。