|
| 1 | +// Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +package io.flutter.plugins.packageinfo; |
| 6 | + |
| 7 | +import android.app.Activity; |
| 8 | +import android.content.Context; |
| 9 | +import android.content.pm.PackageInfo; |
| 10 | +import android.content.pm.PackageManager; |
| 11 | +import io.flutter.plugin.common.MethodCall; |
| 12 | +import io.flutter.plugin.common.MethodChannel; |
| 13 | +import io.flutter.plugin.common.MethodChannel.MethodCallHandler; |
| 14 | +import io.flutter.plugin.common.MethodChannel.Result; |
| 15 | +import io.flutter.plugin.common.PluginRegistry.Registrar; |
| 16 | + |
| 17 | +/** PackageInfoPlugin */ |
| 18 | +public class PackageInfoPlugin implements MethodCallHandler { |
| 19 | + private final Context context; |
| 20 | + |
| 21 | + /** Plugin registration. */ |
| 22 | + public static void registerWith(Registrar registrar) { |
| 23 | + final MethodChannel channel = |
| 24 | + new MethodChannel(registrar.messenger(), "plugins.flutter.io/package_info"); |
| 25 | + channel.setMethodCallHandler(new PackageInfoPlugin(registrar.activity())); |
| 26 | + } |
| 27 | + |
| 28 | + private PackageInfoPlugin(Activity activity) { |
| 29 | + this.context = activity; |
| 30 | + } |
| 31 | + |
| 32 | + @Override |
| 33 | + public void onMethodCall(MethodCall call, Result result) { |
| 34 | + try { |
| 35 | + PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0); |
| 36 | + switch (call.method) { |
| 37 | + case "getVersion": |
| 38 | + result.success(info.versionName); |
| 39 | + break; |
| 40 | + case "getBuildNumber": |
| 41 | + result.success(String.valueOf(info.versionCode)); |
| 42 | + break; |
| 43 | + default: |
| 44 | + result.notImplemented(); |
| 45 | + } |
| 46 | + } catch (PackageManager.NameNotFoundException ex) { |
| 47 | + result.error("Name not found", ex.getMessage(), null); |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments