我有一个小项目,我需要使用Android设备的电池。起初,我希望能够打印电池,所以我使用了tutorial。
然后,我在Eclipse中创建了一个名为“Testing”的新Android项目,而在MainActivity.java中我放了这段代码:
package com.example.testing;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
import android.R.*;
public class MainActivity extends Activity {
TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.MainActivity); //This is the MainActivity that contains the error
mTextView = (TextView) findViewById(R.id.batterTest);
findViewById(R.id.getBattery).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTextView.setText(String.valueOf(batteryLevel));
}
});
new Thread(new ThreadM()).start();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mArrow);
}
BatteryReceiver mArrow;
private class ThreadM implements Runnable {
@Override
public void run() {
mArrow = new BatteryReceiver();
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);
mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
mIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
Intent batteryIntent = registerReceiver(mArrow, mIntentFilter);
batteryLevel = getBatteryLevel(batteryIntent);
Log.e("Battery Level", String.valueOf(batteryLevel));
}
}
float batteryLevel;
private class BatteryReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_LOW) || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_CHANGED) || arg1.getAction().equalsIgnoreCase(Intent.ACTION_BATTERY_OKAY)) {
int level = arg1.getIntExtra("level", 0);
Toast.makeText(MainActivity.this,"Current Battery " + level + " %", Toast.LENGTH_LONG).show();
mTextView.setText(String.valueOf("Battery Level Change Detect through Receiver = " + level));
}
}
}
public float getBatteryLevel(Intent batteryIntent) {
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (level == -1 || scale == -1) {
return 50.0f;
}
return ((float) level / (float) scale) * 100.0f;
}
}
实际上,这应该只是在屏幕上打印电池电量的情况下运行一个简单的活动。但它并不是因为一个错误。 “MainActivity无法解析或不是字段”(请参阅注释行)。 你知道为什么吗?我想让这段代码工作,这样我就可以继续了。
谢谢。
答案 0 :(得分:9)
您需要更改
setContentView(R.layout.MainActivity);
到
setContentView(R.layout.activity_main);
假设您有一个名为activity_main.xml
而不是MainActivity
的布局,它实际上是您的Activity类的名称
并删除
import android.R.*;
并导入
import com.example.testing.R;