Remove old platform messaging API (#8837)

Breaking change: removed deprecated methods of PlatformMessages, leaving only binary messaging there. All other use of platform communication now goes through PlatformMessageChannel and PlatformMethodChannels. Retained use of String and JSON codecs for now.

Companion engine PR: flutter/engine#3482
This commit is contained in:
Mikkel Nygaard Ravn
2017-03-17 11:56:50 +01:00
committed by GitHub
parent 3d3900871a
commit dce4bf8599
39 changed files with 578 additions and 555 deletions

View File

@@ -1,44 +1,39 @@
package com.example.flutter;
import android.app.Instrumentation;
import android.graphics.Bitmap;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import io.flutter.view.FlutterView;
import android.app.Instrumentation;
import android.support.test.InstrumentationRegistry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import io.flutter.plugin.common.FlutterMethodChannel;
import io.flutter.view.FlutterView;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Rule
public ActivityTestRule<ExampleActivity> activityRule =
new ActivityTestRule<>(ExampleActivity.class);
new ActivityTestRule<>(ExampleActivity.class);
@Test
public void testFlutterMessage() {
final Instrumentation instr = InstrumentationRegistry.getInstrumentation();
final JSONObject message = new JSONObject();
final int RANDOM_MIN = 1;
final int RANDOM_MAX = 1000;
try {
message.put("min", RANDOM_MIN);
message.put("max", RANDOM_MAX);
} catch (JSONException e) {
fail(e.getMessage());
}
final CountDownLatch latch = new CountDownLatch(1);
final AtomicInteger random = new AtomicInteger();
@@ -46,17 +41,18 @@ public class ExampleInstrumentedTest {
instr.runOnMainSync(new Runnable() {
public void run() {
final FlutterView flutterView = (FlutterView) activityRule.getActivity().findViewById(
R.id.flutter_view);
flutterView.sendToFlutter("getRandom", message.toString(), new FlutterView.MessageReplyCallback() {
public void onReply(String json) {
try {
JSONObject reply = new JSONObject(json);
random.set(reply.getInt("value"));
} catch (JSONException e) {
fail(e.getMessage());
} finally {
latch.countDown();
}
R.id.flutter_view);
final FlutterMethodChannel randomChannel = new FlutterMethodChannel(flutterView, "random");
randomChannel.invokeMethod("getRandom", Arrays.asList(RANDOM_MIN, RANDOM_MAX), new FlutterMethodChannel.Response() {
@Override
public void success(Object o) {
random.set(((Number) o).intValue());
latch.countDown();
}
@Override
public void error(String code, String message, Object details) {
}
});
}
@@ -78,7 +74,7 @@ public class ExampleInstrumentedTest {
instr.runOnMainSync(new Runnable() {
public void run() {
final FlutterView flutterView = (FlutterView) activityRule.getActivity().findViewById(
R.id.flutter_view);
R.id.flutter_view);
// Call onPostResume to start the engine's renderer even if the activity
// is paused in the test environment.
@@ -105,13 +101,23 @@ public class ExampleInstrumentedTest {
// Waits on a FlutterView until it is able to produce a bitmap.
private class BitmapPoller {
private final int delayMsec = 1000;
private int triesPending;
private int waitMsec;
private FlutterView flutterView;
private Bitmap bitmap;
private CountDownLatch latch = new CountDownLatch(1);
private final int delayMsec = 1000;
private Runnable checkBitmap = new Runnable() {
public void run() {
bitmap = flutterView.getBitmap();
triesPending--;
if (bitmap != null || triesPending == 0) {
latch.countDown();
} else {
flutterView.postDelayed(checkBitmap, delayMsec);
}
}
};
BitmapPoller(int tries) {
triesPending = tries;
@@ -127,17 +133,5 @@ public class ExampleInstrumentedTest {
latch.await(waitMsec, TimeUnit.MILLISECONDS);
return bitmap;
}
private Runnable checkBitmap = new Runnable() {
public void run() {
bitmap = flutterView.getBitmap();
triesPending--;
if (bitmap != null || triesPending == 0) {
latch.countDown();
} else {
flutterView.postDelayed(checkBitmap, delayMsec);
}
}
};
}
}

View File

@@ -6,28 +6,26 @@ 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.plugin.common.FlutterMethodChannel;
import io.flutter.plugin.common.MethodCall;
import io.flutter.view.FlutterMain;
import io.flutter.view.FlutterView;
import java.io.File;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class ExampleActivity extends Activity {
private static final String TAG = "ExampleActivity";
private FlutterView flutterView;
private FlutterMethodChannel randomChannel;
@Override
public void onCreate(Bundle savedInstanceState) {
@@ -39,20 +37,24 @@ public class ExampleActivity extends Activity {
flutterView = (FlutterView) findViewById(R.id.flutter_view);
flutterView.runFromBundle(FlutterMain.findAppBundlePath(getApplicationContext()), null);
flutterView.addOnMessageListener("getLocation",
new FlutterView.OnMessageListener() {
@Override
public String onMessage(FlutterView view, String message) {
return onGetLocation(message);
FlutterMethodChannel locationChannel = new FlutterMethodChannel(flutterView, "location");
randomChannel = new FlutterMethodChannel(flutterView, "random");
locationChannel.setMethodCallHandler(new FlutterMethodChannel.MethodCallHandler() {
@Override
public void onMethodCall(MethodCall methodCall, FlutterMethodChannel.Response response) {
if (methodCall.method.equals("getLocation")) {
getLocation((String) methodCall.arguments, response);
} else {
response.error("unknown method", "Unknown method: " + methodCall.method, null);
}
});
}
});
Button getRandom = (Button) findViewById(R.id.get_random);
getRandom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendGetRandom();
}
public void onClick(View v) { getRandom(); }
});
}
@@ -76,79 +78,44 @@ public class ExampleActivity extends Activity {
flutterView.onPostResume();
}
private void sendGetRandom() {
JSONObject message = new JSONObject();
try {
message.put("min", 1);
message.put("max", 1000);
} catch (JSONException e) {
Log.e(TAG, "JSON exception", e);
return;
}
private void getRandom() {
randomChannel.invokeMethod("getRandom", Arrays.asList(1, 1000), new FlutterMethodChannel.Response() {
TextView textView = (TextView) findViewById(R.id.random_value);
flutterView.sendToFlutter("getRandom", message.toString(),
new FlutterView.MessageReplyCallback() {
@Override
public void onReply(String json) {
onRandomReply(json);
}
});
@Override
public void success(Object result) {
textView.setText(result.toString());
}
@Override
public void error(String code, String message, Object details) {
textView.setText("Error: " + message);
}
});
}
private void onRandomReply(String json) {
double value;
try {
JSONObject reply = new JSONObject(json);
value = reply.getDouble("value");
} catch (JSONException e) {
Log.e(TAG, "JSON exception", e);
return;
}
TextView randomValue = (TextView) findViewById(R.id.random_value);
randomValue.setText(Double.toString(value));
}
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, FlutterMethodChannel.Response response) {
String locationProvider;
if (provider.equals("network")) {
locationProvider = LocationManager.NETWORK_PROVIDER;
} else if (provider.equals("gps")) {
locationProvider = LocationManager.GPS_PROVIDER;
} else {
return null;
response.error("unknown provider", "Unknown location provider: " + provider, null);
return;
}
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(Arrays.asList(location.getLatitude(), location.getLongitude()));
} else {
reply.put("latitude", 0);
reply.put("longitude", 0);
response.error("location unavailable", "Location is not available", null);
}
} catch (JSONException e) {
Log.e(TAG, "JSON exception", e);
return null;
} else {
response.error("access error", "Location permissions not granted", null);
}
return reply.toString();
}
}

View File

@@ -13,7 +13,6 @@
9740EEB41CF90195004384FC /* Flutter.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 9740EEB21CF90195004384FC /* Flutter.xcconfig */; };
9740EEB51CF90195004384FC /* Generated.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 9740EEB31CF90195004384FC /* Generated.xcconfig */; };
9740EEBB1CF902C7004384FC /* app.flx in Resources */ = {isa = PBXBuildFile; fileRef = 9740EEB71CF902C7004384FC /* app.flx */; };
977505191CFDF23500BC28DA /* LocationProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 977505181CFDF23500BC28DA /* LocationProvider.m */; };
97A38A351CFDEC880099F1B4 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 97A38A341CFDEC880099F1B4 /* AppDelegate.m */; };
97C146F31CF9000F007C117D /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 97C146F21CF9000F007C117D /* main.m */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
@@ -42,8 +41,6 @@
9740EEB71CF902C7004384FC /* app.flx */ = {isa = PBXFileReference; lastKnownFileType = file; name = app.flx; path = Flutter/app.flx; sourceTree = "<group>"; };
9740EEB81CF902C7004384FC /* app.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = app.dylib; path = Flutter/app.dylib; sourceTree = "<group>"; };
9740EEBA1CF902C7004384FC /* Flutter.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Flutter.framework; path = Flutter/Flutter.framework; sourceTree = "<group>"; };
977505171CFDF21E00BC28DA /* LocationProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = LocationProvider.h; sourceTree = "<group>"; };
977505181CFDF23500BC28DA /* LocationProvider.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = LocationProvider.m; sourceTree = "<group>"; };
97A38A331CFDEC680099F1B4 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = "<group>"; };
97A38A341CFDEC880099F1B4 /* AppDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = "<group>"; };
97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -105,8 +102,6 @@
97C146F11CF9000F007C117D /* Supporting Files */,
97A38A331CFDEC680099F1B4 /* AppDelegate.h */,
97A38A341CFDEC880099F1B4 /* AppDelegate.m */,
977505171CFDF21E00BC28DA /* LocationProvider.h */,
977505181CFDF23500BC28DA /* LocationProvider.m */,
);
path = Runner;
sourceTree = "<group>";

View File

@@ -5,24 +5,34 @@
#import "AppDelegate.h"
#import <Flutter/Flutter.h>
#import "LocationProvider.h"
#import <CoreLocation/CoreLocation.h>
@implementation AppDelegate {
LocationProvider* _locationProvider;
CLLocationManager* _locationManager;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
FlutterDartProject* project = [[FlutterDartProject alloc] initFromDefaultSourceForConfiguration];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
FlutterViewController* flutterController = [[FlutterViewController alloc] initWithProject:project
nibName:nil
bundle:nil];
_locationProvider = [[LocationProvider alloc] init];
[flutterController addMessageListener:_locationProvider];
self.window.rootViewController = flutterController;
[self.window makeKeyAndVisible];
return YES;
- (BOOL)application:(UIApplication*)application
didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
FlutterViewController* controller =
(FlutterViewController*)self.window.rootViewController;
FlutterMethodChannel* locationChannel = [FlutterMethodChannel
methodChannelNamed:@"location"
binaryMessenger:controller
codec:[FlutterStandardMethodCodec sharedInstance]];
[locationChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResultReceiver result) {
if ([@"getLocation" isEqualToString:call.method]) {
if (_locationManager == nil) {
_locationManager = [[CLLocationManager alloc] init];
[_locationManager startMonitoringSignificantLocationChanges];
}
CLLocation* location = _locationManager.location;
result(@[@(location.coordinate.latitude), @(location.coordinate.longitude)], nil);
} else {
result(nil, [FlutterError errorWithCode:@"unknown method"
message:@"Unknown location method called"
details:nil]);
}
}];
return YES;
}
@end

View File

@@ -1,8 +1,12 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
@@ -14,9 +18,9 @@
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>

View File

@@ -1,21 +1,26 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="6211" systemVersion="14A298i" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16D32" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6204"/>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModuleProvider="" sceneMemberID="viewController">
<viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>

View File

@@ -1,9 +0,0 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import <Flutter/Flutter.h>
@interface LocationProvider : NSObject <FlutterMessageListener>
@end

View File

@@ -1,39 +0,0 @@
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#import "LocationProvider.h"
#import <CoreLocation/CoreLocation.h>
@implementation LocationProvider {
CLLocationManager* _locationManager;
}
@synthesize messageName = _messageName;
- (instancetype) init {
self = [super init];
if (self)
self->_messageName = @"getLocation";
return self;
}
- (NSString*)didReceiveString:(NSString*)message {
if (_locationManager == nil) {
_locationManager = [[CLLocationManager alloc] init];
[_locationManager startMonitoringSignificantLocationChanges];
}
CLLocation* location = _locationManager.location;
NSDictionary* response = @{
@"latitude": @(location.coordinate.latitude),
@"longitude": @(location.coordinate.longitude),
};
NSData* data = [NSJSONSerialization dataWithJSONObject:response options:0 error:nil];
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
@end

View File

@@ -10,13 +10,14 @@ import 'package:flutter/services.dart';
final Random random = new Random();
Future<dynamic> handleGetRandom(Map<String, dynamic> message) async {
final double min = message['min'].toDouble();
final double max = message['max'].toDouble();
final PlatformMethodChannel randomChannel = new PlatformMethodChannel('random');
return <String, double>{
'value': (random.nextDouble() * (max - min)) + min
};
Future<dynamic> handleGetRandom(MethodCall call) async {
if (call.method == 'getRandom') {
final int min = call.arguments[0];
final int max = call.arguments[1];
return random.nextInt(max - min) + min;
}
}
class HelloServices extends StatefulWidget {
@@ -25,8 +26,8 @@ class HelloServices extends StatefulWidget {
}
class _HelloServicesState extends State<HelloServices> {
double _latitude;
double _longitude;
static PlatformMethodChannel locationChannel = new PlatformMethodChannel('location');
String _location = 'Press button to get location';
@override
Widget build(BuildContext context) {
@@ -38,32 +39,37 @@ class _HelloServicesState extends State<HelloServices> {
new Text('Hello from Flutter!'),
new RaisedButton(
child: new Text('Get Location'),
onPressed: _getLocation
onPressed: _getLocation,
),
new Text('Latitude: $_latitude, Longitude: $_longitude'),
]
)
)
new Text(_location),
],
),
),
);
}
Future<Null> _getLocation() async {
final Map<String, String> message = <String, String>{'provider': 'network'};
final Map<String, dynamic> reply = await PlatformMessages.sendJSON('getLocation', message);
String location;
try {
final List<double> reply = await locationChannel.invokeMethod(
'getLocation',
'network',
);
location = 'Latitude: ${reply[0]}, Longitude: ${reply[1]}';
} on PlatformException catch(e) {
location = 'Error: ' + e.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;
if (!mounted) return;
setState(() {
_latitude = reply['latitude'].toDouble();
_longitude = reply['longitude'].toDouble();
_location = location;
});
}
}
void main() {
runApp(new HelloServices());
PlatformMessages.setJSONMessageHandler('getRandom', handleGetRandom);
randomChannel.setMethodCallHandler(handleGetRandom);
}