Исф*_*нов 6 java android dart flutter
我正在尝试从来电中获取电话号码,对于 Android,我一直在尝试实现这个答案,但我一直在努力,因为答案不完整,没有示例,而且非常抽象,这对于一个对平台渠道没有任何了解的人来说是很困难的。
\n我尝试过的:\n我在 ServiceReceiver 中实现了鸽子代码,声明了一个我想要更新并传递给 flutter 代码的变量,但是当我接到电话时,应用程序甚至不要求任何权限,这让我认为手机接到来电时不会调用 onReceive() 函数。
\n这是代码:
\n主要.dart:
\nimport \'package:flutter/material.dart\';\nimport \'package:flutter/services.dart\';\nimport \'./output.dart\';\n\nvoid main() {\n runApp(MyApp());\n}\n\n// void onClick() async {\n// SearchRequest request = SearchRequest()..query = \'test\';\n// Api api = Api();\n// SearchReply reply = await api.search(request);\n// print(\'reply: ${reply.result}\');\n// }\n\nclass MyApp extends StatefulWidget {\n // This widget is the root of your application.\n @override\n _MyAppState createState() => _MyAppState();\n}\n\nclass _MyAppState extends State<MyApp> {\n static const platform = const MethodChannel(\'battery.ttsollution.com\');\n String _phoneNumber = \'\';\n String _batteryLevel = \'Unknown battery level.\';\n\n void onClick() async {\n SearchRequest request = SearchRequest()..query = \'test\';\n Api api = Api();\n SearchReply reply = await api.search(request);\n print(\'reply: ${reply.result}\');\n }\n\n Future<void> _getPhoneNumber() async {\n String phoneNumber;\n try {\n final int result = await platform.invokeMethod(\'getPhoneNumber\');\n phoneNumber = "Phone number: $result";\n } catch (e) {\n phoneNumber = "Failed to get the phone number due to: $e";\n }\n setState(() {\n _phoneNumber = phoneNumber;\n });\n }\n\n Future<void> _getBatteryLevel() async {\n String batteryLevel;\n try {\n final int result = await platform.invokeMethod(\'getBatteryLevel\');\n batteryLevel = \'Battery level at $result % .\';\n } on PlatformException catch (e) {\n batteryLevel = "Failed to get battery level: \'${e.message}\'.";\n }\n\n setState(() {\n _batteryLevel = batteryLevel;\n });\n }\n\n @override\n Widget build(BuildContext context) {\n return MaterialApp(\n home: Scaffold(\n body: Center(\n child: Column(\n mainAxisAlignment: MainAxisAlignment.spaceEvenly,\n children: [\n ElevatedButton(\n child: Text(\'Get Phone Number\'),\n onPressed: onClick,\n ),\n Text(_batteryLevel),\n ],\n ),\n ),\n ),\n );\n }\n}\nRun Code Online (Sandbox Code Playgroud)\nMainActivity.java:
\npackage com.example.phone_application_java;\n\nimport androidx.annotation.NonNull;\nimport androidx.annotation.RequiresApi;\n\nimport io.flutter.embedding.android.FlutterActivity;\nimport io.flutter.embedding.engine.FlutterEngine;\nimport io.flutter.plugin.common.MethodChannel;\n\nimport android.content.Context;\nimport android.content.ContextWrapper;\nimport android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.BatteryManager;\nimport android.os.Build.VERSION;\nimport android.os.Build.VERSION_CODES;\nimport android.os.Bundle;\nimport android.telephony.TelephonyManager;\n\npublic class MainActivity extends FlutterActivity {\n private static final String CHANNEL = "battery.ttsollution.com";\n\n\n @RequiresApi(api = VERSION_CODES.M)\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Pigeon.Api.setup(getFlutterEngine().getDartExecutor().getBinaryMessenger(), new ServiceReceiver.MyApi());\n }\n\n @Override\n public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {\n super.configureFlutterEngine(flutterEngine);\n new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)\n .setMethodCallHandler((call, result) -> {\n // Note: this method is invoked on the main thread.\n if (call.method.equals("getBatteryLevel")) {\n int batteryLevel = getBatteryLevel();\n\n if (batteryLevel != -1) {\n result.success(batteryLevel);\n } else {\n result.error("UNAVAILABLE", "Battery level not available.", null);\n }\n } else {\n result.notImplemented();\n }\n });\n }\n\n private int getBatteryLevel() {\n int batteryLevel = -1;\n if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {\n BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);\n batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);\n } else {\n Intent intent = new ContextWrapper(getApplicationContext()).registerReceiver(null,\n new IntentFilter(Intent.ACTION_BATTERY_CHANGED));\n batteryLevel = (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100)\n / intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);\n }\n\n return batteryLevel;\n }\n\n}\nRun Code Online (Sandbox Code Playgroud)\n服务接收器.java:
\npackage com.example.phone_application_java;\n\nimport android.annotation.SuppressLint;\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.telephony.PhoneStateListener;\nimport android.telephony.TelephonyManager;\nimport android.os.Bundle;\n\nimport com.example.phone_application_java.Pigeon;\n\npublic class ServiceReceiver extends BroadcastReceiver {\n static String phoneNumber = "Hiya";\n\n static class MyApi implements Pigeon.Api {\n @Override\n public Pigeon.SearchReply search(Pigeon.SearchRequest arg) {\n Pigeon.SearchReply reply = new Pigeon.SearchReply();\n reply.setResult(ServiceReceiver.phoneNumber);\n return reply;\n }\n }\n\n\n @SuppressLint("UnsafeProtectedBroadcastReceiver")\n @Override\n public void onReceive(Context context, Intent intent) {\n TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);\n telephony.listen(new PhoneStateListener() {\n @Override\n public void onCallStateChanged(int state, String incomingNumber) {\n super.onCallStateChanged(state, incomingNumber);\n System.out.println("incomingNumber : " + incomingNumber);\n phoneNumber = incomingNumber;\n }\n }, PhoneStateListener.LISTEN_CALL_STATE);\n }\n\n}\nRun Code Online (Sandbox Code Playgroud)\nAndroidManifest.xml:
\n<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.phone_application_java">\n <uses-permission android:name="android.permission.READ_PHONE_STATE" />\n <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>\n <uses-permission android:name="android.permission.READ_CALL_LOG" />\n <application android:label="phone_application_java" android:icon="@mipmap/ic_launcher">\n\n <receiver android:name=".ServiceReceiver">\n <intent-filter>\n <action android:name="android.intent.action.PHONE_STATE" />\n <action android:name="android.intent.action.NEW_OUTGOING_CALL" />\n </intent-filter>\n </receiver>\n <activity android:name=".MainActivity" android:launchMode="singleTop" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize">\n <!-- Specifies an Android theme to apply to this Activity as soon as\n the Android process has started. This theme is visible to the user\n while the Flutter UI initializes. After that, this theme continues\n to determine the Window background behind the Flutter UI. -->\n <meta-data android:name="io.flutter.embedding.android.NormalTheme" android:resource="@style/NormalTheme" />\n <!-- Displays an Android View that continues showing the launch screen\n Drawable until Flutter paints its first frame, then this splash\n screen fades out. A splash screen is useful to avoid any visual\n gap between the end of Android\'s launch screen and the painting of\n Flutter\'s first frame. -->\n <meta-data android:name="io.flutter.embedding.android.SplashScreenDrawable" android:resource="@drawable/launch_background" />\n <intent-filter>\n <action android:name="android.intent.action.MAIN" />\n <category android:name="android.intent.category.LAUNCHER" />\n </intent-filter>\n </activity>\n <!-- Don\'t delete the meta-data below.\n This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->\n <meta-data android:name="flutterEmbedding" android:value="2" />\n </application>\n</manifest>\nRun Code Online (Sandbox Code Playgroud)\n颤振医生:
\nPS E:\\Flutter Projects\\phone_application_java> flutter doctor\nDoctor summary (to see all details, run flutter doctor -v):\n[\xe2\x88\x9a] Flutter (Channel stable, 2.0.6, on Microsoft Windows [Version 10.0.19042.928], locale en-US)\n[\xe2\x88\x9a] Android toolchain - develop for Android devices (Android SDK version 30.0.3)\n[\xe2\x88\x9a] Chrome - develop for the web\n[\xe2\x88\x9a] Android Studio (version 4.1.0)\n[\xe2\x88\x9a] Connected device (3 available)\n\n\xe2\x80\xa2 No issues found!\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
980 次 |
| 最近记录: |