Android蓝牙应用程序崩溃第二项活动

时间:2015-10-23 04:44:39

标签: android bluetooth

大家好我经过多次努力后真的很累我发布这个问题请帮助。应用程序崩溃不知道为什么。任何帮助将不胜感激。 请帮助我使用android studio。

DEVICELISTACTIVITY

package com.smarthomeASAD.echohome;

import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DeviceListActivity extends Activity {
    // Debugging for LOGCAT
    private static final String TAG = "DeviceListActivity";
    // private static final boolean D = true;

    // declare button for launching website and textview for connection status
    Button tlbutton;
    TextView textView1;

    // EXTRA string to send on to mainactivity
    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    // Member fields
    private BluetoothAdapter mBtAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;

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

        super.onResume();
        checkBTState();

        textView1 = (TextView) findViewById(R.id.connecting);
        textView1.setTextSize(40);
        textView1.setText(" ");

        // Initialize array adapter for paired devices
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
                R.layout.device_name);

        // Find and set up the ListView for paired devices
        ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
        pairedListView.setAdapter(mPairedDevicesArrayAdapter);
        pairedListView.setOnItemClickListener(mDeviceClickListener);

        // Get the local Bluetooth adapter
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();

        // Get a set of currently paired devices and append to 'pairedDevices'
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        // Add previosuly paired devices to the array
        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);// make
                                                                                // title
                                                                                // viewable
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevicesArrayAdapter.add(device.getName() + "\n"
                        + device.getAddress());
            }
        } else {
            String noDevices = getResources().getText(R.string.none_paired)
                    .toString();
            mPairedDevicesArrayAdapter.add(noDevices);
        }

        MediaPlayer welcome = MediaPlayer.create(getApplicationContext(),
                R.raw.wlcom);

        welcome.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                // Code to start the next audio in the sequence
                final MediaPlayer selectroom = MediaPlayer.create(
                        getApplicationContext(), R.raw.selectroom);

                selectroom.start();
            }
        });
        welcome.start();

    }

    // Set up on-click listener for the list (nicked this - unsure)
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {

            textView1.setText("Connecting...");
            // Get the device MAC address, which is the last 17 chars in the
            // View
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            // Make an intent to start next activity while taking an extra which
            // is the MAC address.
            Intent i = new Intent(DeviceListActivity.this, MainActivity.class);
            i.putExtra(EXTRA_DEVICE_ADDRESS, address);
            startActivity(i);
            Toast.makeText(getBaseContext(), "main acitvity started...",
                    Toast.LENGTH_LONG).show();
        }
    };

    private void checkBTState() {
        // Check device has Bluetooth and that it is turned on
        mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // CHECK THIS OUT
                                                            // THAT IT WORKS!!!
        if (mBtAdapter == null) {
            Toast.makeText(getBaseContext(),
                    "Device does not support Bluetooth", Toast.LENGTH_SHORT)
                    .show();
        } else {
            if (mBtAdapter.isEnabled()) {
                Log.d(TAG, "...Bluetooth ON...");
            } else {
                // Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);

            }
        }
    }
}

ACTIVITY_MAIN

package com.smarthomeASAD.echohome;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.smarthomeASAD.echohome.R;

public class MainActivity extends Activity {
    public InputStream mmInStream = null;
    public OutputStream mmOutStream = null;
    public boolean connectionfailureb = false;
    Button btnOn, btnOff;
    TextView txtArduino, txtString, txtStringLength, sensorView0, sensorView1,
            sensorView2, sensorView3;
    static Handler bluetoothIn;

    final int handlerState = 0; // used to identify handler message
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private StringBuilder recDataString = new StringBuilder();

    private ConnectedThread mConnectedThread;

    // SPP UUID service - this should work for most devices
    private static final UUID BTMODULEUUID = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");

    // String for MAC address
    private static String address;

    @SuppressLint("HandlerLeak")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        // ==========================TOGGLE BUTTONS=============
        ToggleButton t1 = (ToggleButton) findViewById(R.id.tb1);
        ToggleButton t2 = (ToggleButton) findViewById(R.id.tb2);
        ToggleButton t3 = (ToggleButton) findViewById(R.id.tb3);
        ToggleButton t4 = (ToggleButton) findViewById(R.id.tb4);
        ToggleButton t5 = (ToggleButton) findViewById(R.id.tb5);
        // =========================TOGGLE BUTTONS==============

        // >>>>>>>>>>>>>>>>>>>MEDIA--------------------------
        final MediaPlayer sciencedanger = MediaPlayer.create(
                getApplicationContext(), R.raw.science_fiction_danger_alarm);
        final MediaPlayer motiondetected = MediaPlayer.create(
                getApplicationContext(), R.raw.motion_detected);
        // <<<<<<<<<<<<<<<<<<<MEDIA-<<<<<<<<<<<<<<<<<<<<<<<<
        // Link the buttons and textViews to respective views
        txtString = (TextView) findViewById(R.id.txtString);
        txtStringLength = (TextView) findViewById(R.id.testView1);
        sensorView0 = (TextView) findViewById(R.id.sensorView0);
        sensorView1 = (TextView) findViewById(R.id.sensorView1);
        sensorView2 = (TextView) findViewById(R.id.sensorView2);
        sensorView3 = (TextView) findViewById(R.id.sensorView3);

        bluetoothIn = new Handler() {
            public void handleMessage(android.os.Message msg) {
                if (msg.what == handlerState) { // if message is what we want
                    Log.i("handler", null);
                    String readMessage = (String) msg.obj;
                    recDataString.append(readMessage);
                    int endOfLineIndex = recDataString.indexOf("~");
                    if (endOfLineIndex > 0) { // make sure there data before ~
                        String dataInPrint = recDataString.substring(0,
                                endOfLineIndex); // extract string
                        txtString.setText("Data Received = " + dataInPrint);
                        int dataLength = dataInPrint.length();
                        txtStringLength.setText("String Length = "
                                + String.valueOf(dataLength));

                        if (recDataString.charAt(0) == '#') {
                            String sensor0 = recDataString.substring(1, 5);
                            // =================================================MOD--------------------
                            Log.i("IN RecData", readMessage);
                            if (sensor0.equals("1.00")) {
                                sciencedanger.start();
                                motiondetected.start();
                            } else {
                            }

                            // =================================================MOD--------------------

                            sensorView0.setText(" Sensor 0 Voltage = "
                                    + sensor0);

                        }
                        recDataString.delete(0, recDataString.length());
                        dataInPrint = " ";
                    }
                }
            }
        };

        btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth
                                                            // adapter
        checkBTState();

        // Set up onClick listeners for buttons to send 1 or 0 to turn on/off
        // LED

        // ========================================================
        // ========================================================
        t1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                    try {
                        mConnectedThread.write("1");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "ON", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // The toggle is disabled
                    try {
                        mConnectedThread.write("0");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "OFF", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });
        t2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                    try {
                        mConnectedThread.write("2");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "ON", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // The toggle is disabled
                    try {
                        mConnectedThread.write("3");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "OFF", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });
        t3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                    try {
                        mConnectedThread.write("4");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "ON", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // The toggle is disabled
                    try {
                        mConnectedThread.write("5");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "OFF", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });
        t4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                    try {
                        mConnectedThread.write("6");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "ON", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // The toggle is disabled
                    try {
                        mConnectedThread.write("7");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "OFF", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });
        t5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                    try {
                        mConnectedThread.write("8");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "ON", Toast.LENGTH_SHORT)
                            .show();
                } else {
                    // The toggle is disabled
                    try {
                        mConnectedThread.write("9");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    Toast.makeText(getBaseContext(), "OFF", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });

        // =========================================================
        // ==========================================================
    }

    private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
            throws IOException {

        return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
        // creates secure outgoing connecetion with BT device using UUID
    }

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

        // Get MAC address from DeviceListActivity via intent
        Intent intent = getIntent();

        // Get the MAC address from the DeviceListActivty via EXTRA
        address = intent
                .getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

        // create device and set the MAC address
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "Socket creation failed",
                    Toast.LENGTH_LONG).show();
        }
        // Establish the Bluetooth socket connection.
        try {

            btSocket.connect();
        } catch (IOException e) {
            try {
                mmInStream.close();
                mmOutStream.close();
                btSocket.close();
            } catch (IOException e2) {
                Toast.makeText(getBaseContext(),
                        "closing exception btSocket sonnection problem",
                        Toast.LENGTH_LONG).show();
                // insert code to deal with this
            }
        }
        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();

        // I send a character when resuming.beginning transmission to check
        // device is connected
        // If it is not an exception will be thrown in the write method and
        // finish() will be called
        try {
            mConnectedThread.write("x");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Toast.makeText(getBaseContext(), "Thread can't write",
                    Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        try {
            // Don't leave Bluetooth sockets open when leaving activity
            btSocket.close();
        } catch (IOException e2) {
            // insert code to deal with this
        }
    }

    // Checks that the Android device Bluetooth is available and prompts to be
    // turned on if off
    private void checkBTState() {

        if (btAdapter == null) {
            Toast.makeText(getBaseContext(),
                    "Device does not support bluetooth", Toast.LENGTH_LONG)
                    .show();
        } else {
            if (btAdapter.isEnabled()) {
            } else {
                Intent enableBtIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    // create new class for connect thread
    private class ConnectedThread extends Thread {

        // creation of the connect thread
        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try {
                // Create I/O streams for connection
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        // =================================================MOD--------------------

        public void run() {
            byte[] buffer = new byte[256];
            int bytes;

            // Keep looping to listen for received messages
            while (true) {
                try {
                    bytes = mmInStream.read(buffer); // read bytes from input
                                                        // buffer
                    String readMessage = new String(buffer, 0, bytes); // Send
                                                                        // the
                                                                        // obtained
                                                                        // bytes
                                                                        // to
                                                                        // the
                                                                        // UI
                                                                        // Activity
                                                                        // via
                                                                        // handler
                    bluetoothIn.obtainMessage(handlerState, bytes, -1,
                            readMessage).sendToTarget();
                } catch (IOException e) {
                    Toast.makeText(getBaseContext(), "listner eror",
                            Toast.LENGTH_LONG).show();
                    break;
                }
            }
        }

        // =================================================MOD--------------------
        // write method
        public void write(String input) throws InterruptedException {
            byte[] msgBuffer = input.getBytes(); // converts entered String into
                                                    // bytes
            try {
                mmOutStream.write(msgBuffer); // write bytes over BT connection
                                                // via outstream
                MediaPlayer connected = MediaPlayer.create(
                        getApplicationContext(), R.raw.connected);
                connected.start();
            } catch (IOException e) {

                // if you cannot write, close the application
                final MediaPlayer connectionfailure = MediaPlayer.create(
                        getApplicationContext(), R.raw.connectionfailure);
                connectionfailure
                        .setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                // Code to start the next audio in the sequence
                                Toast.makeText(getBaseContext(),
                                        "Connection Failure", Toast.LENGTH_LONG)
                                        .show();
                                finish();
                            }
                        });
                connectionfailure.start();

            }
            Thread.sleep(1000);

        }
    }
}

logcat的

 10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime: FATAL EXCEPTION: main
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime: java.lang.RuntimeException: Unable to resume activity {com.smarthomeASAD.echohome/com.smarthomeASAD.echohome.MainActivity}: java.lang.NullPointerException
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2918)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2947)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2382)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.access$600(ActivityThread.java:167)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:153)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5341)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:  Caused by: java.lang.NullPointerException
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at com.smarthomeASAD.echohome.MainActivity.onResume(MainActivity.java:288)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1190)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.Activity.performResume(Activity.java:5203)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2905)
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2947) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2382) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.access$600(ActivityThread.java:167) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:153) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5341) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696) 
10-22 17:43:19.712 32054-32054/com.smarthomeASAD.echohome E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

public class ClassB { public event MyEventHandler MyEvent; public delegate void MyEventHandler(object sender, MyEventArgs e); public class MyEventArgs : EventArgs { public MyEventArgs() { } } private virtual void OnMyEvent(MyEventArgs e) { MyEventHandler handler = MyEvent; if (handler != null) { handler(this, e); } } public ClassB() { /// do stuff } public void Method() { OnMyEvent(new MyEventArgs()); } } public class ClassA { private ClassB member = new ClassB(); public ClassA() { /// do stuff } public void Method() { member.Method(); } } static class Program { static List<ClassA> aList = new List<ClassA>(); static void Main() { aList.Add(new ClassA()); /// I would like to be able to do this... aList[0].MyEvent += MyEvent_handler; aList[0].Method(); } void MyEvent_handler(object sender, ClassB.MyEventArgs e) { /// ... such that sender is the ClassA instance i.e. aList[0] /// and e is the MyEventArgs passed to OnMyEvent in ClassB } } 中,无论何时使用意图,都必须添加空检查。执行onResume()时,它实际上可能会返回空意图