mirror of
https://github.com/flutter/samples.git
synced 2026-04-06 11:41:26 +00:00
[federated_plugin_sample] modify the sample to expose battery API instead of geolocation API (#526)
This commit is contained in:
@@ -40,5 +40,4 @@ android {
|
||||
|
||||
dependencies {
|
||||
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
|
||||
implementation 'com.google.android.gms:play-services-location:17.0.0'
|
||||
}
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
package="dev.flutter.federated_plugin">
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
</manifest>
|
||||
|
||||
@@ -4,109 +4,55 @@
|
||||
|
||||
package dev.flutter.federated_plugin
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.BatteryManager
|
||||
import android.os.Build
|
||||
import androidx.annotation.NonNull
|
||||
import androidx.core.app.ActivityCompat.requestPermissions
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.google.android.gms.location.LocationServices.getFusedLocationProviderClient
|
||||
|
||||
import io.flutter.embedding.engine.plugins.FlutterPlugin
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityAware
|
||||
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
|
||||
import io.flutter.plugin.common.MethodChannel.Result
|
||||
import io.flutter.plugin.common.PluginRegistry
|
||||
|
||||
|
||||
class FederatedPlugin : FlutterPlugin, MethodCallHandler, ActivityAware, PluginRegistry.RequestPermissionsResultListener {
|
||||
class FederatedPlugin : FlutterPlugin, MethodCallHandler {
|
||||
private lateinit var channel: MethodChannel
|
||||
private lateinit var context: Context
|
||||
private lateinit var activity: Activity
|
||||
private lateinit var result: Result
|
||||
private val REQUEST_CODE = 1001
|
||||
private var context: Context? = null
|
||||
|
||||
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
|
||||
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "location")
|
||||
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "battery")
|
||||
channel.setMethodCallHandler(this)
|
||||
context = flutterPluginBinding.applicationContext
|
||||
}
|
||||
|
||||
override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
|
||||
this.result = result
|
||||
if (call.method == "getLocation") {
|
||||
// Check for the runtime permission if SDK version is greater than 23. If permissions
|
||||
// are granted, send the location data back to Dart. If permissions are not granted,
|
||||
// request for the runtime permissions.
|
||||
if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP && !checkPermissions()) {
|
||||
requestPermissions(activity, arrayOf(
|
||||
Manifest.permission.ACCESS_FINE_LOCATION,
|
||||
Manifest.permission.ACCESS_COARSE_LOCATION
|
||||
), REQUEST_CODE)
|
||||
if (call.method == "getBatteryLevel") {
|
||||
val batteryLevel: Int
|
||||
|
||||
batteryLevel = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
|
||||
val batteryManager = context?.getSystemService(Context.BATTERY_SERVICE) as BatteryManager
|
||||
batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
|
||||
} else {
|
||||
provideLocation()
|
||||
val intent = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { intentFilter ->
|
||||
context?.registerReceiver(null, intentFilter)
|
||||
}
|
||||
intent!!.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100 / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
|
||||
}
|
||||
|
||||
if (batteryLevel < 0) {
|
||||
result.error("STATUS_UNAVAILABLE", "Not able to determine battery level.", null)
|
||||
} else {
|
||||
result.success(batteryLevel)
|
||||
}
|
||||
} else {
|
||||
result.notImplemented()
|
||||
}
|
||||
}
|
||||
|
||||
// Method to fetch and send the last known location of the device to Dart.
|
||||
private fun provideLocation() {
|
||||
getFusedLocationProviderClient(context).lastLocation
|
||||
.addOnSuccessListener { location ->
|
||||
if (location != null) {
|
||||
result.success(listOf(location.longitude, location.latitude))
|
||||
} else {
|
||||
result.error("NOT_DETERMINED", "Not able to determine location", null)
|
||||
}
|
||||
}.addOnFailureListener { exception ->
|
||||
result.error("Error", exception.message, null)
|
||||
}
|
||||
}
|
||||
|
||||
// Method to check permissions to access the location data.
|
||||
private fun checkPermissions(): Boolean {
|
||||
val fineLocationPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
val coarseLocationPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
|
||||
return fineLocationPermission == PackageManager.PERMISSION_GRANTED &&
|
||||
coarseLocationPermission == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
|
||||
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
|
||||
channel.setMethodCallHandler(null)
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivity() {}
|
||||
|
||||
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
}
|
||||
|
||||
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
|
||||
activity = binding.activity
|
||||
binding.addRequestPermissionsResultListener(this)
|
||||
}
|
||||
|
||||
override fun onDetachedFromActivityForConfigChanges() {}
|
||||
|
||||
// Callback for the result after requesting for runtime permissions. If permissions
|
||||
// are granted, send the location data, or send an error back to Dart if permissions
|
||||
// are not granted.
|
||||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?, grantResults: IntArray): Boolean {
|
||||
if (requestCode == REQUEST_CODE && grantResults.isNotEmpty()) {
|
||||
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
|
||||
provideLocation()
|
||||
} else {
|
||||
result.error("PERMISSION_DENIED", "Permission denied from User", null)
|
||||
}
|
||||
}
|
||||
return false
|
||||
context = null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,15 +18,15 @@ class MyApp extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// Demonstrates how to use the getLocation method from federated_plugin to access
|
||||
/// location data.
|
||||
/// Demonstrates how to use the getBatteryLevel method from federated_plugin to retrieve
|
||||
/// current battery level of device.
|
||||
class HomePage extends StatefulWidget {
|
||||
@override
|
||||
_HomePageState createState() => _HomePageState();
|
||||
}
|
||||
|
||||
class _HomePageState extends State<HomePage> {
|
||||
Location location;
|
||||
int batteryLevel;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
@@ -40,21 +40,20 @@ class _HomePageState extends State<HomePage> {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
location == null
|
||||
batteryLevel == null
|
||||
? SizedBox.shrink()
|
||||
: Text(
|
||||
'Latitude: ${location.latitude}\n'
|
||||
'Longitude: ${location.longitude}',
|
||||
'Battery Level: $batteryLevel',
|
||||
style: Theme.of(context).textTheme.headline5,
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
RaisedButton(
|
||||
child: Text('Get Location'),
|
||||
child: Text('Get Battery Level'),
|
||||
onPressed: () async {
|
||||
try {
|
||||
final result = await getLocation();
|
||||
final result = await getBatteryLevel();
|
||||
setState(() {
|
||||
location = result;
|
||||
batteryLevel = result;
|
||||
});
|
||||
} catch (error) {
|
||||
Scaffold.of(context).showSnackBar(
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
// Use of this source code is governed by a BSD-style license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
import 'package:federated_plugin/federated_plugin.dart';
|
||||
import 'package:federated_plugin_example/main.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
@@ -10,27 +9,23 @@ import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
group('federated plugin demo tests', () {
|
||||
final location = Location(latitude: 131.0, longitude: 221.0);
|
||||
final batteryLevel = 45;
|
||||
setUpAll(() {
|
||||
MethodChannel('location').setMockMethodCallHandler((call) async {
|
||||
if (call.method == 'getLocation') {
|
||||
return [location.longitude, location.latitude];
|
||||
MethodChannel('battery').setMockMethodCallHandler((call) async {
|
||||
if (call.method == 'getBatteryLevel') {
|
||||
return batteryLevel;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
testWidgets('get location from platform', (tester) async {
|
||||
testWidgets('get current battery level from platform', (tester) async {
|
||||
await tester.pumpWidget(MyApp());
|
||||
|
||||
// Tap button to get location from platform.
|
||||
// Tap button to retrieve current battery level from platform.
|
||||
await tester.tap(find.byType(RaisedButton));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(
|
||||
find.text('Latitude: ${location.latitude}\n'
|
||||
'Longitude: ${location.longitude}'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('Battery Level: $batteryLevel'), findsOneWidget);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,12 +5,10 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:federated_plugin_platform_interface/federated_plugin_platform_interface.dart';
|
||||
import 'package:federated_plugin_platform_interface/location_model.dart';
|
||||
export 'package:federated_plugin_platform_interface/location_model.dart';
|
||||
|
||||
/// Returns [Location] to provide latitude and longitude.
|
||||
/// Returns the current battery level of device.
|
||||
///
|
||||
/// It uses [FederatedPluginInterface] interface to provide location.
|
||||
Future<Location> getLocation() async {
|
||||
return await FederatedPluginInterface.instance.getLocation();
|
||||
/// It uses [FederatedPluginInterface] interface to provide current battery level.
|
||||
Future<int> getBatteryLevel() async {
|
||||
return await FederatedPluginInterface.instance.getBatteryLevel();
|
||||
}
|
||||
|
||||
@@ -10,17 +10,16 @@ void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
group('Federated Plugin Test', () {
|
||||
final location = Location(latitude: 131.0, longitude: 221.0);
|
||||
MethodChannel('location').setMockMethodCallHandler((call) async {
|
||||
if (call.method == 'getLocation') {
|
||||
return [location.longitude, location.latitude];
|
||||
final batteryLevel = 34;
|
||||
MethodChannel('battery').setMockMethodCallHandler((call) async {
|
||||
if (call.method == 'getBatteryLevel') {
|
||||
return batteryLevel;
|
||||
}
|
||||
});
|
||||
|
||||
test('getLocation method test', () async {
|
||||
final result = await getLocation();
|
||||
expect(result.longitude, location.longitude);
|
||||
expect(result.latitude, location.latitude);
|
||||
test('getBatteryLevel method test', () async {
|
||||
final result = await getBatteryLevel();
|
||||
expect(result, batteryLevel);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user