Flutter应用管理插件tizen_app_manager的使用

Flutter应用管理插件tizen_app_manager的使用

<img src="https://img.shields.io/pub/v/tizen_app_manager.svg" alt="pub package">

tizen_app_manager

Tizen应用管理API。用于在Tizen设备上获取应用信息和应用运行上下文。

使用

要使用此包,将<code>tizen_app_manager</code>作为依赖项添加到您的<code>pubspec.yaml</code>文件中。

dependencies:
  tizen_app_manager: ^0.2.3

获取当前应用信息

要检索当前应用的信息,通过<code>AppManager.currentAppId</code>获取应用ID,然后使用<code>AppManager.getAppInfo</code>获取<code>AppInfo</code>

import 'package:tizen_app_manager/tizen_app_manager.dart';

String appId = await AppManager.currentAppId;
AppInfo appInfo = await AppManager.getAppInfo(appId);

获取所有应用信息

要检索所有已安装应用的信息,使用<code>AppManager.getInstalledApps</code>

List<AppInfo> apps = await AppManager.getInstalledApps();
for (AppInfo app in apps) {
  // 处理每个应用的信息。
}

获取应用运行上下文

要获取特定应用的运行上下文,创建一个带有目标应用ID的<code>AppRunningContext</code>实例。

String appId = await AppManager.currentAppId;
AppRunningContext appContext = AppRunningContext(appId: appId);

监听应用事件

可以通过订阅<code>AppManager.onAppLaunched</code><code>AppManager.onAppTerminated</code>来监听应用状态的变化。

var subscription = AppManager.onAppLaunched.listen((AppRunningContext context) {
  String appId = context.appId;
});
...
subscription.cancel();

必需的权限

以下权限可能需要使用此插件。请将所需的权限添加到应用程序的<code>tizen-manifest.xml</code>文件中。

<privileges>
  <privilege>http://tizen.org/privilege/appmanager.launch</privilege>
  <privilege>http://tizen.org/privilege/appmanager.kill.bgapp</privilege>
  <privilege>http://tizen.org/privilege/appmanager.kill</privilege>
</privileges>
  • <code>http://tizen.org/privilege/appmanager.launch</code>权限由<code>AppRunningContext.resume()</code>所需。
  • <code>http://tizen.org/privilege/appmanager.kill.bgapp</code>权限由<code>AppRunningContext.terminate(background: true)</code>所需。
  • <code>http://tizen.org/privilege/appmanager.kill</code>权限由<code>AppRunningContext.terminate(background: false)</code>所需。注意,这是一个平台级别的权限,不能授予第三方应用程序。

以下是完整的示例代码:

// Copyright 2022 Samsung Electronics Co., Ltd. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:async';
import 'dart:io';

import 'package:device_info_plus_tizen/device_info_plus_tizen.dart';
import 'package:flutter/material.dart';
import 'package:tizen_app_control/tizen_app_control.dart';
import 'package:tizen_app_manager/tizen_app_manager.dart';

/// 应用设置的App ID。
const String settingsAppId = 'org.tizen.setting';

/// 可穿戴模拟器设置的App ID。
const String wearableSettingsAppId = 'org.tizen.watch-setting';

/// 电视模拟器音量设置的App ID。
const String tvVolumeSettingAppId = 'org.tizen.volume-setting';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App Manager Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  [@override](/user/override)
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 3,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('App Manager Demo'),
          bottom: const TabBar(
            isScrollable: true,
            tabs: [
              Tab(text: 'This app'),
              Tab(text: 'App list'),
              Tab(text: 'App events'),
            ],
          ),
        ),
        body: const TabBarView(
          children: [
            _CurrentAppScreen(),
            _AppListScreen(),
            _AppEventsScreen(),
          ],
        ),
      ),
    );
  }
}

class _CurrentAppScreen extends StatefulWidget {
  const _CurrentAppScreen();

  [@override](/user/override)
  State<_CurrentAppScreen> createState() => _CurrentAppScreenState();
}

class _CurrentAppScreenState extends State<_CurrentAppScreen> {
  final Future<AppInfo> _appInfo = () async {
    final String appId = await AppManager.currentAppId;
    return AppManager.getAppInfo(appId);
  }();

  Widget _infoTile(String title, String subtitle) {
    return ListTile(title: Text(title), subtitle: Text(subtitle));
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return FutureBuilder<AppInfo>(
      future: _appInfo,
      builder: (BuildContext context, AsyncSnapshot<AppInfo> snapshot) {
        if (snapshot.hasData) {
          final AppInfo appInfo = snapshot.data!;
          final AppRunningContext appContext =
              AppRunningContext(appId: appInfo.appId);
          return ListView(
            children: [
              _infoTile('App ID', appInfo.appId),
              _infoTile('Package ID', appInfo.packageId),
              _infoTile('Label', appInfo.label),
              _infoTile('Type', appInfo.appType),
              _infoTile('Executable path', appInfo.executablePath),
              _infoTile('Shared resource path', appInfo.sharedResourcePath),
              _infoTile('Metadata', appInfo.metadata.toString()),
              _infoTile('Process ID', appContext.processId.toString()),
              _infoTile('State', appContext.appState.name),
            ],
          );
        } else if (snapshot.hasError) {
          return Center(child: Text(snapshot.error.toString()));
        } else {
          return const Center(child: CircularProgressIndicator());
        }
      },
    );
  }
}

class _AppListScreen extends StatefulWidget {
  const _AppListScreen();

  [@override](/user/override)
  State<_AppListScreen> createState() => _AppListScreenState();
}

class _AppListScreenState extends State<_AppListScreen>
    with AutomaticKeepAliveClientMixin {
  [@override](/user/override)
  bool get wantKeepAlive => true;

  [@override](/user/override)
  Widget build(BuildContext context) {
    super.build(context);

    return FutureBuilder<List<AppInfo>>(
      future: AppManager.getInstalledApps(),
      builder: (BuildContext context, AsyncSnapshot<List<AppInfo>> snapshot) {
        if (snapshot.hasData) {
          final List<AppInfo> apps = snapshot.data!;
          return ListView.builder(
            itemCount: apps.length,
            itemBuilder: (BuildContext context, int index) {
              final AppInfo appInfo = apps[index];
              Widget appIcon = const Icon(Icons.error_outline);
              if (appInfo.iconPath != null) {
                final File iconFile = File(appInfo.iconPath!);
                if (iconFile.existsSync()) {
                  appIcon = Image.file(iconFile);
                }
              }
              return ListTile(
                leading: SizedBox(width: 30, child: appIcon),
                title: Text(appInfo.label),
                subtitle: Text(appInfo.packageId),
                trailing: Text(
                  appInfo.appType,
                  style: Theme.of(context).textTheme.bodySmall,
                ),
              );
            },
          );
        } else if (snapshot.hasError) {
          return Center(child: Text(snapshot.error.toString()));
        } else {
          return const Center(child: CircularProgressIndicator());
        }
      },
    );
  }
}

class _AppEvent {
  _AppEvent({
    required this.event,
    required this.appId,
    required this.processId,
  });

  final String event;
  final String appId;
  final int processId;
}

class _AppEventsScreen extends StatefulWidget {
  const _AppEventsScreen();

  [@override](/user/override)
  State<_AppEventsScreen> createState() => _AppEventsScreenState();
}

class _AppEventsScreenState extends State<_AppEventsScreen>
    with AutomaticKeepAliveClientMixin {
  late final StreamSubscription<AppRunningContext>? _launchSubscription;
  late final StreamSubscription<AppRunningContext>? _terminateSubscription;
  final List<_AppEvent> _appEvents = [];
  String _settingsAppId = settingsAppId;

  [@override](/user/override)
  bool get wantKeepAlive => true;

  [@override](/user/override)
  void initState() {
    super.initState();

    _getDeviceInfo();

    _launchSubscription =
        AppManager.onAppLaunched.listen((AppRunningContext context) {
      setState(() {
        _appEvents.add(_AppEvent(
          event: 'Launched',
          appId: context.appId,
          processId: context.processId,
        ));
      });
    });
    _terminateSubscription =
        AppManager.onAppTerminated.listen((AppRunningContext context) {
      setState(() {
        _appEvents.add(_AppEvent(
          event: 'Terminated',
          appId: context.appId,
          processId: context.processId,
        ));
      });
    });
  }

  Future<void> _getDeviceInfo() async {
    final DeviceInfoPluginTizen deviceInfo = DeviceInfoPluginTizen();
    final TizenDeviceInfo tizenInfo = await deviceInfo.tizenInfo;
    setState(() {
      if (tizenInfo.profile == 'tv') {
        _settingsAppId = tvVolumeSettingAppId;
      } else if (tizenInfo.profile == 'wearable') {
        _settingsAppId = wearableSettingsAppId;
      }
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    super.build(context);

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Padding(
          padding: const EdgeInsets.all(10),
          child: ElevatedButton(
            onPressed: () {
              AppControl(appId: _settingsAppId).sendLaunchRequest();
            },
            child: Text('Launch $_settingsAppId'),
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _appEvents.length,
            itemBuilder: (BuildContext context, int index) {
              final _AppEvent event = _appEvents.elementAt(index);
              return ListTile(
                title: Text(event.appId),
                subtitle: Text('Process ID: ${event.processId}'),
                trailing: Text(
                  event.event,
                  style: Theme.of(context).textTheme.bodySmall,
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  [@override](/user/override)
  void dispose() {
    super.dispose();
    _launchSubscription?.cancel();
    _terminateSubscription?.cancel();
  }
}

更多关于Flutter应用管理插件tizen_app_manager的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter应用管理插件tizen_app_manager的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter应用中使用tizen_app_manager插件的一个代码示例。tizen_app_manager插件允许你管理Tizen设备上的应用程序,例如安装、卸载和查询应用状态。

首先,你需要确保已经在你的pubspec.yaml文件中添加了tizen_app_manager依赖:

dependencies:
  flutter:
    sdk: flutter
  tizen_app_manager: ^最新版本号  # 请替换为实际发布的最新版本号

然后运行flutter pub get来安装依赖。

以下是一个简单的示例,展示如何使用tizen_app_manager插件来查询设备上已安装的应用列表:

import 'package:flutter/material.dart';
import 'package:tizen_app_manager/tizen_app_manager.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<TizenAppInfo> _installedApps = [];

  @override
  void initState() {
    super.initState();
    _getInstalledApps();
  }

  Future<void> _getInstalledApps() async {
    TizenAppManager appManager = TizenAppManager();
    try {
      List<TizenAppInfo> apps = await appManager.getInstalledApps();
      setState(() {
        _installedApps = apps;
      });
    } catch (e) {
      print('Error getting installed apps: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Tizen App Manager Example'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: _installedApps.isEmpty
              ? Center(child: CircularProgressIndicator())
              : ListView.builder(
                  itemCount: _installedApps.length,
                  itemBuilder: (BuildContext context, int index) {
                    TizenAppInfo appInfo = _installedApps[index];
                    return ListTile(
                      title: Text(appInfo.appName),
                      subtitle: Text('ID: ${appInfo.appId}'),
                    );
                  },
                ),
        ),
      ),
    );
  }
}

class TizenAppInfo {
  String appId;
  String appName;
  // 根据需要添加更多属性

  TizenAppInfo({required this.appId, required this.appName});

  factory TizenAppInfo.fromMap(Map<String, dynamic> map) {
    return TizenAppInfo(
      appId: map['appId'] as String,
      appName: map['appName'] as String,
      // 根据需要解析更多属性
    );
  }
}

请注意,上面的代码中有几个重要的地方需要注意:

  1. TizenAppManager的实例化TizenAppManager()是插件提供的主要类,用于管理应用。
  2. 获取已安装应用列表getInstalledApps()方法返回一个包含设备上所有已安装应用信息的列表。
  3. 错误处理:捕获并处理可能发生的异常。
  4. 数据展示:使用Flutter的ListView.builder来展示应用列表。

需要注意的是,tizen_app_manager插件的具体API可能会随着版本的更新而有所变化,因此请务必查阅最新的官方文档以获取最准确的信息。此外,实际使用中可能还需要处理权限问题,确保你的应用有权限访问设备上的应用信息。

这个示例主要展示了如何获取并展示已安装的应用列表,你可以根据需求扩展功能,比如安装、卸载应用等。

回到顶部