实际上我正在尝试制作一个Android应用程序,当电池变为50%时显示文本,m使用文本视图显示消息,但在加载应用程序时,它很快就会停止。
这是我的代码:
Java文件。
package com.example.abhi.batteryalarm;
import android.content.Intent;
import android.os.BatteryManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Battery_Alarm extends ActionBarActivity {
Intent batteryStatus;
TextView txtView;
String hello;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_battery__alarm);
txtView=(TextView)findViewById(R.id.txtView);
hello="This is my first project";
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
if (level==50)
{
txtView.setText(hello);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_battery__alarm, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
活动档案:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Battery_Alarm">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"
android:textSize="62sp"
android:id="@+id/txtView"
android:layout_centerHorizontal="true"
android:layout_marginBottom="125dp" />
</RelativeLayout>
我需要做什么?
答案 0 :(得分:1)
添加此内容,
batteryStatus = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
之前,
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
它会起作用。
答案 1 :(得分:0)
这是导致错误的行:
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
这是因为batteryStatus意图永远不会被初始化,因此是空的。
查看有关获取电池电量的答案:https://stackoverflow.com/a/4047790/1239966
答案 2 :(得分:0)
您需要注册batteryStatus。
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);