从另一个类调用函数

时间:2013-07-22 07:09:24

标签: android class chat installation

我正在使用BluetoothChat示例创建一个Android应用程序。

我需要将de bluetooth配置活动与聊天活动分开,因此,我有一个主要活动,其中包含用于启用/可发现蓝牙的按钮,以及另一个用于转到聊天活动的按钮。

这些功能与示例相同,但我将它们划分为2个活动。

问题是我需要从主活动调用SetupChat()函数,在启用蓝牙时调用此函数。但是我在聊天活动中有这个功能,因为此活动中还有其他变量依赖于它。

那么,如何从主要活动中调用此函数?

我已经介绍了一些方法。如果函数是静态的,我可以毫无问题地调用它,但它是一个公共空白。我不能把这个函数放在一个简单的类中,因为它调用了“findviewbyid”函数,它需要在一个活动中。

那么,我怎么称它为?

我在这里举办了展位活动:

这是MainActivity:

public class BTActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button button1 = (Button) findViewById(R.id.boton1);
    final Button button2 = (Button) findViewById(R.id.boton2);
    final Button button4 = (Button) findViewById(R.id.boton4);
    final Button button5 = (Button) findViewById(R.id.boton5);

    button5.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            lanzarComunicacion (null);
        }
    });


    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LanzarBusqueda(null);

        }
    });

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mBluetoothAdapter.isDiscovering()) {

                Context context = getApplicationContext();
                CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();

                Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);

                startActivity(discoverableIntent);
            }
        }
    });

    button4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mBluetoothAdapter.disable();

            //out.append("TURN_OFF BLUETOOTH");
            Context context = getApplicationContext();
            CharSequence text = "TURNING_OFF BLUETOOTH";
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, text, 15);
            toast.show();

        }
    });
}


@Override
public void onStart() {
    super.onStart();

    if (!mBluetoothAdapter.isEnabled()) {

        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    }
    else {
        //HERE IS THE FIRST PLACE WHERE IT IS CALLED
        if (mTransmission == null) BTCommunication.setupChat();
    }
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data);
            }
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session  
                //HERE IS CALLED                
                //BTCommunication.setupChat();
            } else {
                // User did not enable Bluetooth or an error occurred
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
            break;
    }

}


private void connectDevice(Intent data) {
    Toast.makeText(getApplicationContext(), "LLEGA", Toast.LENGTH_SHORT).show();
    // Get the device MAC address
    String address = data.getExtras().getString(DeviceListDialog.EXTRA_DEVICE_ADDRESS);
    // Get the BluetoothDevice object
    BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
    // Attempt to connect to the device
    mTransmission.connect(device);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.bt, menu);
    return true;
}


/** Intent de llamada a activity de comunicacion*/
public void lanzarComunicacion (View view) {
    Intent i = new Intent(this, BTCommunication.class);
    startActivity(i);
}

/** Intent de llamada a dialogo de busqueda de dispositivos*/
public void LanzarBusqueda (View view) {
    Intent serverintent = new Intent(this, DeviceListDialog.class);
    startActivityForResult(serverintent, REQUEST_CONNECT_DEVICE);
}

}

/这是聊天活动:

public class BTCommunication extends Activity {


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

    // Performing this check in onResume() covers the case in which BT was
    // not enabled during onStart(), so we were paused to enable it...
    // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
    if (mTransmission != null) {
        // Only if the state is STATE_NONE, do we know that we haven't started already
        if (mTransmission.getState() == Transmission.STATE_NONE) {
            // Start the Bluetooth chat services
            mTransmission.start();
        }
    }
}



public void setupChat() {
    // Initialize the array adapter for the conversation thread
    mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
    mConversationView = (ListView) findViewById(R.id.in);
    mConversationView.setAdapter(mConversationArrayAdapter);

    // Initialize the compose field with a listener for the return key
    mOutEditText = (EditText) findViewById(R.id.edit_text_out);
    mOutEditText.setOnEditorActionListener(mWriteListener);

    // Initialize the send button with a listener that for click events
    mSendButton = (Button) findViewById(R.id.button_send);
    mSendButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Send a message using content of the edit text widget
            TextView view = (TextView) findViewById(R.id.edit_text_out);
            String message = view.getText().toString();
            sendMessage(message);
        }
    });

    // Initialize the Transmission to perform bluetooth connections
    mTransmission = new Transmission(this, mHandler);

    // Initialize the buffer for outgoing messages
    mOutStringBuffer = new StringBuffer("");
}



@Override
public void onDestroy() {
    super.onDestroy();
    // Stop the Bluetooth chat services
    if (mTransmission != null) mTransmission.stop();
}


/**
 * Sends a message.
 * @param message  A string of text to send.
 */
public void sendMessage(String message) {
    // Check that we're actually connected before trying anything
    if (mTransmission.getState() != Transmission.STATE_CONNECTED) {
        Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
        return;
    }

    // Check that there's actually something to send
    if (message.length() > 0) {
        // Get the message bytes and tell the BluetoothChatService to write
        byte[] send = message.getBytes();
        mTransmission.write(send);

        // Reset out string buffer to zero and clear the edit text field
        mOutStringBuffer.setLength(0);
        mOutEditText.setText(mOutStringBuffer);
    }
}

// The action listener for the EditText widget, to listen for the return key
private final TextView.OnEditorActionListener mWriteListener = new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
        // If the action is a key-up event on the return key, send the message
        if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
            String message = view.getText().toString();
            sendMessage(message);
        }
        return true;
    }
};



private final void setStatus(int resId) {
    final ActionBar actionBar = getActionBar();
    actionBar.setSubtitle(resId);
}

private final void setStatus(CharSequence subTitle) {
    final ActionBar actionBar = getActionBar();
    actionBar.setSubtitle(subTitle);
}



// The Handler that gets information back from the Transmission
private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                switch (msg.arg1) {
                    case Transmission.STATE_CONNECTED:
                        setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
                        mConversationArrayAdapter.clear();
                        break;
                    case Transmission.STATE_CONNECTING:
                        setStatus(R.string.title_connecting);
                        break;
                    case Transmission.STATE_LISTEN:
                    case Transmission.STATE_NONE:
                        setStatus(R.string.title_not_connected);
                        break;
                }
                break;
            case MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(readBuf, 0, msg.arg1);
                mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to " + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
                break;
        }
    }
};

}

1 个答案:

答案 0 :(得分:0)

通常情况下,我有两种方法可以解决这个问题。

  1. mainacvitity提供公共静态实例

  2. 使用经理类来保存mainacvitity的实例

相关问题