Flutter中的本机代码有问题

时间:2019-03-30 01:43:13

标签: dart flutter

我试图在flutter应用程序中添加本机android代码以获取用户位置数据,但每次收到错误时:未处理的异常:MissingPluginException(在通道sample.flutter.io/location上未找到方法getLongitude的实现)

我的MainActivity.java文件是:

package com.example.alert_on_crises;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;

import io.flutter.app.FlutterActivity;

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 android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity implements LocationListener {
    public static final String CHANNEL = "samples.flutter.io/location";
    private LocationManager locationManager;
    private String provider;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GeneratedPluginRegistrant.registerWith(this);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        provider = LocationManager.GPS_PROVIDER;

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider);
        new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(new MethodChannel.MethodCallHandler() {
            @Override
            public void onMethodCall(MethodCall call, Result result) {
                System.out.println(call.method);
                if (call.method.equals("getLongitude")) {
                    Location location = locationManager.getLastKnownLocation(provider);

                    if (location != null) {
                        System.out.println("Provider " + provider + " has been selected.");
                        int lat = (int) (location.getLatitude());
                        int lng = getLongitude(location);
                        int coordinates[] = { lat, lng };

                        result.success(lng);
                    } else {
                        result.error("UNAVAILABLE", "Location not available.", null);
                    }


                } else {
                    result.notImplemented();
                }    // TODO
            }

        });
        // getLocation();
    }

    int getLongitude(Location location){
        int lng = (int) (location.getLongitude());
        return lng;
    }

    protected void onResume() {
        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(provider, 400, 0, this);
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d("location change:", " change1  " );
        int lat = (int) (location.getLatitude());
        int lng = (int) (location.getLongitude());
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    // private void getLocation() {
    //     if (ContextCompat.checkSelfPermission(this, android.android.Manifest.permission.ACCESS_FINE_LOCATION) !=
    //         PackageManager.PERMISSION_GRANTED) {
    //         ActivityCompat.requestPermissions(this,
    //             new String[] {
    //                 android.Manifest.permission.ACCESS_FINE_LOCATION
    //             },
    //             10);

    //     } else {
    //         locationManager.getLastKnownLocation(provider)
    //             .addOnSuccessListener(this, new OnSuccessListener < Location > () {
    //                 @Override
    //                 public void onSuccess(Location location) {
    //                     // Got last known location. In some rare situations this can be null.
    //                     if (location != null) {
    //                         // use location.getLatitude() and location.getLongitude()

    //                     }
    //                 }
    //             });
    //     }

    // }

    // @Override
    // public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    //     switch (requestCode) {
    //         case 10:
    //             {
    //                 // If request is cancelled, the result arrays are empty.
    //                 if (grantResults.length > 0 &&
    //                     grantResults[0] == PackageManager.PERMISSION_GRANTED) {
    //                     // getLocation();
    //                 } else {
    //                     // permission denied, boo! Disable the
    //                     // functionality that depends on this permission.
    //                 }
    //                 return;
    //             }
    //     }
    // }
}

在我的dart文件中调用上述功能的代码是:

class _DistressAlertScreenState extends State<DistressAlertScreen> {
  static const platform = const MethodChannel('samples.flutter.io/location');

Future<void> _getUserLocation() async {
    String userLocation;
    try {
      final int result = await platform.invokeMethod('getLongitude');
      print('Coordinates are ${result}');
    } on PlatformException catch (e) {
      print('Error fetching coordinates ${e.message}');
    }
    // print(userLocation);
    // setState(() {
    //   _userLocation = userLocation;
    // });
  }
}

请任何人帮助我了解我在此代码中做错了什么,得到上述错误

0 个答案:

没有答案