2017-04-02 113 views
0

我想使用廣播接收機與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

回答

1

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

似乎是在類定義,而不是在方法。 如果是這樣,那麼它將返回null,因爲ContentView沒有被設置,直到OnCreate,而這個定義發生在對象創建時。

+0

Thanx。幫助很多 –

+0

@SilentCoder你爲什麼「不接受」我的回答?任何原因? – theblitz

+0

我接受了你的答案。也許我沒有足夠的聲望投票。 –

相關問題