我想使用廣播接收機與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>
您錯過了堆棧跟蹤 – efekctive