MethodChannel-Native 端
为简单起见,本例的Android端代码都直接写在MainActivity
中。Android平台下获取电量是通过调用BatteryManager来获取的,所以我们先在MainActivity
中增加一个获取电量的函数:
private int getBatteryLevel() {
int batteryLevel = -1;
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
} else {
Intent intent = new ContextWrapper(getApplicationContext()).
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
}
return batteryLevel;
}
这个函数需要能被Flutter app调用,此时就需要通过MethodChannel
来建立这个通道了。 首先在MainActivity
的onCreate
函数中加入以下代码来新建一个MethodChannel
public class MainActivity extends FlutterActivity {
//channel的名称,由于app中可能会有多个channel,这个名称需要在app内是唯一的。
private static final String CHANNEL = “samples.flutter.io/battery”;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreat