PlatformXxxChannel concepts added to support Flutter/platform interop (#8394)

New concepts: PlatformMessageChannel (basic message send/receive superseding some existing  PlatformMessages methods), PlatformMethodChannel (method invocation and event streams), pluggable codecs for messages and method calls: unencoded binary, string, json, and 'standard' flutter binary encoding.
This commit is contained in:
Mikkel Nygaard Ravn
2017-03-01 14:35:41 +01:00
committed by GitHub
parent 41d81132f9
commit 390993d070
15 changed files with 1206 additions and 71 deletions

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.platformservices"
package="com.example.flutter"
android:versionCode="1"
android:versionName="0.0.1">

View File

@@ -4,85 +4,60 @@
package com.example.flutter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import io.flutter.app.FlutterActivity;
import io.flutter.view.FlutterMain;
import io.flutter.plugin.common.FlutterMethodChannel;
import io.flutter.plugin.common.FlutterMethodChannel.MethodCallHandler;
import io.flutter.plugin.common.FlutterMethodChannel.Response;
import io.flutter.plugin.common.MethodCall;
import io.flutter.view.FlutterView;
import java.io.File;
import org.json.JSONException;
import org.json.JSONObject;
public class ExampleActivity extends FlutterActivity {
private static final String TAG = "ExampleActivity";
private FlutterView flutterView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
flutterView = getFlutterView();
flutterView.addOnMessageListener("getLocation",
new FlutterView.OnMessageListener() {
@Override
public String onMessage(FlutterView view, String message) {
return onGetLocation(message);
new FlutterMethodChannel(getFlutterView(), "geo").setMethodCallHandler(new MethodCallHandler() {
@Override
public void onMethodCall(MethodCall call, Response response) {
if (call.method.equals("getLocation")) {
if (!(call.arguments instanceof String)) {
throw new IllegalArgumentException("Invalid argument type, String expected");
}
getLocation((String) call.arguments, response);
} else {
throw new IllegalArgumentException("Unknown method " + call.method);
}
});
}
});
}
private String onGetLocation(String json) {
String provider;
try {
JSONObject message = new JSONObject(json);
provider = message.getString("provider");
} catch (JSONException e) {
Log.e(TAG, "JSON exception", e);
return null;
}
private void getLocation(String provider, Response response) {
String locationProvider;
if (provider.equals("network")) {
locationProvider = LocationManager.NETWORK_PROVIDER;
} else if (provider.equals("gps")) {
locationProvider = LocationManager.GPS_PROVIDER;
} else {
return null;
throw new IllegalArgumentException("Unknown provider " + provider);
}
String permission = "android.permission.ACCESS_FINE_LOCATION";
Location location = null;
if (checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
location = locationManager.getLastKnownLocation(locationProvider);
}
JSONObject reply = new JSONObject();
try {
Location location = locationManager.getLastKnownLocation(locationProvider);
if (location != null) {
reply.put("latitude", location.getLatitude());
reply.put("longitude", location.getLongitude());
response.success(new double[] { location.getLatitude(), location.getLongitude() });
} else {
reply.put("latitude", 0);
reply.put("longitude", 0);
response.error("unknown", "Location unknown", null);
}
} catch (JSONException e) {
Log.e(TAG, "JSON exception", e);
return null;
} else {
response.error("permission", "Access denied", null);
}
return reply.toString();
}
}
}

View File

@@ -13,8 +13,7 @@ class PlatformServices extends StatefulWidget {
}
class _PlatformServicesState extends State<PlatformServices> {
double _latitude;
double _longitude;
Future<dynamic> _locationRequest;
@override
Widget build(BuildContext context) {
@@ -26,28 +25,42 @@ class _PlatformServicesState extends State<PlatformServices> {
new Text('Hello from Flutter!'),
new RaisedButton(
child: new Text('Get Location'),
onPressed: _getLocation
onPressed: _requestLocation,
),
new Text('Latitude: $_latitude, Longitude: $_longitude'),
]
)
)
new FutureBuilder<dynamic>(
future: _locationRequest,
builder: _buildLocation,
),
],
),
),
);
}
Future<Null> _getLocation() async {
final Map<String, String> message = <String, String>{'provider': 'network'};
final Map<String, dynamic> reply = await PlatformMessages.sendJSON('getLocation', message);
// If the widget was removed from the tree while the message was in flight,
// we want to discard the reply rather than calling setState to update our
// non-existent appearance.
if (!mounted)
return;
void _requestLocation() {
setState(() {
_latitude = reply['latitude'].toDouble();
_longitude = reply['longitude'].toDouble();
_locationRequest = const PlatformMethodChannel('geo').invokeMethod(
'getLocation',
'network',
);
});
}
Widget _buildLocation(BuildContext context, AsyncSnapshot<dynamic> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return new Text('Press button to request location');
case ConnectionState.waiting:
return new Text('Awaiting response...');
default:
try {
final List<double> location = snapshot.requireData;
return new Text('Lat. ${location[0]}, Long. ${location[1]}');
} on PlatformException catch (e) {
return new Text('Request failed: ${e.message}');
}
}
}
}
void main() {