gpt4 book ai didi

android - 如何在flutter App中接听电话?

转载 作者:行者123 更新时间:2023-12-02 14:13:31 25 4
gpt4 key购买 nike

我会尝试以尽可能简单的方式提出问题。如果我的应用在前台运行,并且我当时接到电话,当发生这种情况时,有什么方法可以调用函数/执行操作吗?

// My App is open at any random time call received
(if call_Received) { // How do I do this bit via dart code?
sample()
}

void sample() { // Any random function
// Some code to perform
}

最佳答案

请查看https://pub.dev/packages/phone_state 。我相信它会对你有用。如果您仍有问题,请告诉我。

示例 fragment :

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:phone_state/phone_state.dart';

main() {
runApp(
const MaterialApp(
home: Example(),
),
);
}

class Example extends StatefulWidget {
const Example({Key? key}) : super(key: key);

@override
_ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
PhoneStateStatus status = PhoneStateStatus.NOTHING;
bool granted = false;

Future<bool> requestPermission() async {
var status = await Permission.phone.request();

switch (status) {
case PermissionStatus.denied:
case PermissionStatus.restricted:
case PermissionStatus.limited:
case PermissionStatus.permanentlyDenied:
return false;
case PermissionStatus.granted:
return true;
}
}

@override
void initState() {
super.initState();
if (Platform.isIOS) setStream();
}

void setStream() {
PhoneState.phoneStateStream.listen((event) {
setState(() {
if (event != null) {
status = event;
}
});
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Phone State"),
centerTitle: true,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
if (Platform.isAndroid)
MaterialButton(
child: const Text("Request permission of Phone"),
onPressed: !granted
? () async {
bool temp = await requestPermission();
setState(() {
granted = temp;
if (granted) {
setStream();
}
});
}
: null,
),
const Text(
"Status of call",
style: TextStyle(fontSize: 24),
),
Icon(
getIcons(),
color: getColor(),
size: 80,
)
],
),
),
);
}

IconData getIcons() {
switch (status) {
case PhoneStateStatus.NOTHING:
return Icons.clear;
case PhoneStateStatus.CALL_INCOMING:
return Icons.add_call;
case PhoneStateStatus.CALL_STARTED:
return Icons.call;
case PhoneStateStatus.CALL_ENDED:
return Icons.call_end;
}
}

Color getColor() {
switch (status) {
case PhoneStateStatus.NOTHING:
case PhoneStateStatus.CALL_ENDED:
return Colors.red;
case PhoneStateStatus.CALL_INCOMING:
return Colors.green;
case PhoneStateStatus.CALL_STARTED:
return Colors.orange;
}
}
}

关于android - 如何在flutter App中接听电话?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53675905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com