使用BroadcastReceiver检查电池电量但应用程序崩溃?

问题描述:

我想使用广播接收机与intentfilter ACTION_BATTERY_CHANGED在我的xml中只有一个TextView并将其文本属性设置为某个字符串+应该保存BatteryManager.EXTRA_LEVEL值的整数变量的当前电池级别。但每次尝试启动时,应用都会崩溃。 我错过了什么?使用BroadcastReceiver检查电池电量但应用程序崩溃?

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> 

+0

您错过了堆栈跟踪 – efekctive

线

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

似乎是在类定义,而不是在方法。 如果是这样,那么它将返回null,因为ContentView没有被设置,直到OnCreate,而这个定义发生在对象创建时。

+0

Thanx。帮助很多 –

+0

@SilentCoder你为什么“不接受”我的回答?任何原因? – theblitz

+0

我接受了你的答案。也许我没有足够的声望投票。 –