使用 BroadcastReceiver 检查电池电量但 App 崩溃?

Using BroadcastReceiver to check Battery Level but App crash?

我正在尝试使用带有 intentfilter ACTION_BATTERY_CHANGED 的广播接收器获取当前电池电量 xml 我的 xml 中只有一个 TextView 并将其文本 属性 设置为某个字符串+整数变量应保持 BatteryManager.EXTRA_LEVEL 的值。但是每次尝试启动时应用程序都会崩溃。 我错过了什么吗?

MainActivity.java

public class MainActivity extends AppCompatActivity {
TextView tvcl=(TextView) findViewById(R.id.tvcl);

private BroadcastReceiver bcr=new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int currentLevel=intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
        tvcl.setText("Current Battery Level "+ Integer.toString(currentLevel) + "%");
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    IntentFilter bcFilter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(bcr,bcFilter);
}

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

TextView tvcl=(TextView) findViewById(R.id.tvcl);

似乎在 class 定义中,而不是在方法中。 如果是这样,那么它将 return 为空,因为 ContentView 直到 OnCreate 才被设置,而这个定义发生在对象创建时。