Android Studio - 尝试在状态栏中显示电池温度作为通知

时间:2015-03-15 14:44:43

标签: android battery temperature

我正在使用Android Studio并尝试在状态栏中显示电池温度作为通知。我已成功完成此任务,但有一个问题。温度显示为0.0摄氏度......这是我的代码:

public class SettingsActivity extends ActionBarActivity implements     

OnClickListener
{
Button start, clear;

Notification noti;
NotificationManager nmgr;
public static final int NOTIFICATION_ID = 0;




@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Utils.onActivityCreateSetTheme(this);
    setContentView(R.layout.activity_settings);

    getInit();

    nmgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    noti = new Notification(R.drawable.flame, "Battery Temperature", System.currentTimeMillis());
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

    float temp = ((float) intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)) / 10;


    noti.setLatestEventInfo(this, "Battery Temperature", String.valueOf(temp)  + " C", pIntent);
    noti.flags = Notification.FLAG_ONGOING_EVENT;

}
public void getInit()
{
    findViewById(R.id.btn).setOnClickListener(this);
    findViewById(R.id.btn2).setOnClickListener(this);

    start = (Button) findViewById(R.id.btn3);
    clear = (Button) findViewById(R.id.btn4);
    start.setOnClickListener(this);
    clear.setOnClickListener(this);
}



        @Override
        public void onClick(View v) {
            switch(v.getId())
            {

        case R.id.btn:
            new AlertDialog.Builder(this)
                    .setTitle("Info")
                    .setMessage("Battery Info © 2015 Natan Rosenfeld")
                    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // continue with delete
                        }
                    })
                    .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // do nothing
                        }
                    })
                    .show();
            break;
        case R.id.btn2:
            Intent startcredits = new Intent(this, CreditsActivity.class);
            startActivity(startcredits);
            break;
                case R.id.btn3:
                nmgr.notify(NOTIFICATION_ID,noti);
                break;
                case R.id.btn4:
                nmgr.cancel(NOTIFICATION_ID);


    }

}

}

1 个答案:

答案 0 :(得分:0)

我相信你错过了OnClickListener()方法。 onClickListener()方法将你带到onClick(),所以我没有看到你的代码中你是如何到达onClick()的,因为你从来没有调用它。我是android的新手,但是从我正在编写的应用程序中我一直在使用,并且在创建按钮时看起来似乎是标准:

    button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

    }
});