Flutter Telephony not recieving sms in real hardware except emulator - flutter

I am using telephony dependencies for receive_sms.
It is working fine in the emulator and I receive every message sent, but it is not working on a real hardware phone.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:telephony/telephony.dart';
onBackgroundMessage(SmsMessage message) {
debugPrint("onBackgroundMessage called");
}
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _message = "";
final telephony = Telephony.instance;
#override
void initState() {
super.initState();
initPlatformState();
}
onMessage(SmsMessage message) async {
setState(() {
_message = message.body ?? "Error reading message body.";
});
}
onSendStatus(SendStatus status) {
setState(() {
_message = status == SendStatus.SENT ? "sent" : "delivered";
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
// Platform messages may fail, so we use a try/catch PlatformException.
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
final bool? result = await telephony.requestPhoneAndSmsPermissions;
if (result != null && result) {
telephony.listenIncomingSms(
onNewMessage: onMessage, onBackgroundMessage: onBackgroundMessage);
}
if (!mounted) return;
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(child: Text("Latest received SMS: $_message")),
TextButton(
onPressed: () async {
await telephony.openDialer("123413453");
},
child: Text('Open Dialer'))
],
),
));
}
}
I made sure the correct permissions are added in the Android Manifest file. I asked for the RECEIVE_SMS and BROADCAST_SMS permissions and it appears to be working since I can receive messages in the emulator.
What am I doing wrong?

Try asking for permission before you start listening to the message.
bool permissionsGranted = await telephony.requestPhoneAndSmsPermissions;
here are listed permission required and how to ask.
https://telephony.shounakmulay.dev/permissions

Make sure you added these permission in manifest.
<manifest>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<application>
...
...
<receiver android:name="com.shounakmulay.telephony.sms.IncomingSmsReceiver"
android:permission="android.permission.BROADCAST_SMS" android:exported="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
</manifest>

Related

how to get mobile number in flutter

I am using "mobile_number(version - 1.0.3)" plugin to get mobile number in flutter app, am running in original device but i couldn't get mobile number.instead of errors i can get mobile number as null along with other sim details as shown in screen shot.
help me to resolve this problem, i had just copy pasted the example given by plugin that is the code
plugin link
It says:
Note: If the mobile number is not pre-exist on sim card it will not return te phone number.
I think mobile number does not pre-exist on the SIM if the SIM is not original (i.e. replaced)
If the phone number isn't stored on the sim (aka null), then you can't get it from anywhere else, in that case you probably want to forward the user to a different page where they can type the phone number using TextField and then store it somewhere
Use Mobile_number package to get mobile number and other details. For example
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mobile_number/mobile_number.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _mobileNumber = '';
List<SimCard> _simCard = <SimCard>[];
#override
void initState() {
super.initState();
MobileNumber.listenPhonePermission((isPermissionGranted) {
if (isPermissionGranted) {
initMobileNumberState();
} else {}
});
initMobileNumberState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initMobileNumberState() async {
if (!await MobileNumber.hasPhonePermission) {
await MobileNumber.requestPhonePermission;
return;
}
String mobileNumber = '';
// Platform messages may fail, so we use a try/catch PlatformException.
try {
mobileNumber = (await MobileNumber.mobileNumber)!;
_simCard = (await MobileNumber.getSimCards)!;
} on PlatformException catch (e) {
debugPrint("Failed to get mobile number because of '${e.message}'");
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_mobileNumber = mobileNumber;
});
}
Widget fillCards() {
List<Widget> widgets = _simCard
.map((SimCard sim) => Text(
'Sim Card Number: (${sim.countryPhonePrefix}) - ${sim.number}\nCarrier Name: ${sim.carrierName}\nCountry Iso: ${sim.countryIso}\nDisplay Name: ${sim.displayName}\nSim Slot Index: ${sim.slotIndex}\n\n'))
.toList();
return Column(children: widgets);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text('Running on: $_mobileNumber\n'),
fillCards()
],
),
),
),
);
}
}

In-App Purchase For Google Pay With Flutter

So am trying to use google pay in my flutter application and below is my code. When I run the application is shows google pay dialog with my google pay email and card details and an error "Unrecognised app. Please make sure that you trust this app before proceeding. When I press the "Continue" button I get "Request failed" "Unexpected developer error, please try again later" Please what am I doing wrong?
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:google_pay/google_pay.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
String _googlePayToken = 'Unknown';
#override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await GooglePay.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
await GooglePay.initializeGooglePay("my google play base64EncodedPublicKey");
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text('Running on: $_platformVersion\n'),
Text('Google pay token: $_googlePayToken\n'),
FlatButton(
child: Text("Google Pay Button"),
onPressed: onButtonPressed,
)
]
),
),
),
);
}
void onButtonPressed() async{
setState((){_googlePayToken = "Fetching";});
try {
await GooglePay.openGooglePaySetup(
price: "10.0",
onGooglePaySuccess: onSuccess,
onGooglePayFailure: onFailure,
onGooglePayCanceled: onCancelled);
setState((){_googlePayToken = "Done Fetching";});
} on PlatformException catch (ex) {
setState((){_googlePayToken = "Failed Fetching";});
}
}
void onSuccess(String token){
setState((){_googlePayToken = token;});
}
void onFailure(){
setState((){_googlePayToken = "Failure";});
}
void onCancelled(){
setState((){_googlePayToken = "Cancelled";});
}
} ```
When I run the application is shows google pay dialog with my google pay email and card details and an error "Unrecognised app. Please make sure that you trust this app before proceeding. When I press the "Continue" button I get "Request failed" "Unexpected developer error, please try again later" Please what am I doing wrong?

Download, save as, and change background image of the phone with Flutter

I need help regarding the images in my app. I would like to add 3 buttons for:
Download
Save as
Change phone wallpaper
I'm not using urls. I already have my images in an assets repository.
Do you have any idea how I can do that? Thank you.
You can copy paste run full code below
You can use package https://pub.dev/packages/wallpaper_manager
You can directly set wallpaper with image in assets
Example code's assets image path is "assets/tmp1.jpg"
code snippet
result = await WallpaperManager.setWallpaperFromAsset(
assetPath, WallpaperManager.HOME_SCREEN);
working demo
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:wallpaper_manager/wallpaper_manager.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
String _wallpaperFile = 'Unknown';
String _wallpaperAsset = 'Unknown';
#override
void initState() {
super.initState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await WallpaperManager.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> setWallpaperFromFile() async {
setState(() {
_wallpaperFile = "Loading";
});
String result;
var file = await DefaultCacheManager().getSingleFile(
'https://images.unsplash.com/photo-1542435503-956c469947f6');
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await WallpaperManager.setWallpaperFromFile(
file.path, WallpaperManager.HOME_SCREEN);
} on PlatformException {
result = 'Failed to get wallpaper.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_wallpaperFile = result;
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> setWallpaperFromAsset() async {
setState(() {
_wallpaperAsset = "Loading";
});
String result;
String assetPath = "assets/tmp1.jpg";
// Platform messages may fail, so we use a try/catch PlatformException.
try {
result = await WallpaperManager.setWallpaperFromAsset(
assetPath, WallpaperManager.HOME_SCREEN);
} on PlatformException {
result = 'Failed to get wallpaper.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_wallpaperAsset = result;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Column(
children: <Widget>[
RaisedButton(
child: Text("Platform Version"),
onPressed: initPlatformState,
),
Center(
child: Text('Running on: $_platformVersion\n'),
),
RaisedButton(
child: Text("Set wallpaper from file"),
onPressed: setWallpaperFromFile,
),
Center(
child: Text('Wallpaper status: $_wallpaperFile\n'),
),
RaisedButton(
child: Text("Set wallpaper from asset"),
onPressed: setWallpaperFromAsset,
),
Center(
child: Text('Wallpaper status: $_wallpaperAsset\n'),
),
],
)),
);
}
}

How to detect mock location in flutter for ios and android

I am using package of location and google maps flutter in my screen and I want to detect wether user using fake gps or not.. Is there a package that can detect mock location in flutter that available in android and ios? I have tried using TrustFall package but my app always close unexpectedly.. is there another way to detect mock location in flutter?
Use Geolocator and check the Position object's isMocked property.
you can use TrustLocation
permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
usage :
import 'package:trust_location/trust_location.dart';
/* Assuming in an async function */
/// query the current location.
LatLongPosition position = await TrustLocation.getLatLong;
/// check mock location on Android device.
bool isMockLocation = await TrustLocation.isMockLocation;
using steam:
// input seconds into parameter for getting location with repeating by timer.
// this example set to 5 seconds.
TrustLocation.start(5);
/// the stream getter where others can listen to.
TrustLocation.onChange.listen((values) =>
print('${values.latitude} ${values.longitude} ${values.isMockLocation}')
);
/// stop repeating by timer
TrustLocation.stop();
Example:
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:trust_location/trust_location.dart';
import 'package:location_permissions/location_permissions.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _latitude;
String _longitude;
bool _isMockLocation;
/// initialize state.
#override
void initState() {
super.initState();
requestLocationPermission();
// input seconds into parameter for getting location with repeating by timer.
// this example set to 5 seconds.
TrustLocation.start(5);
getLocation();
}
/// get location method, use a try/catch PlatformException.
Future<void> getLocation() async {
try {
TrustLocation.onChange.listen((values) => setState(() {
_latitude = values.latitude;
_longitude = values.longitude;
_isMockLocation = values.isMockLocation;
}));
} on PlatformException catch (e) {
print('PlatformException $e');
}
}
/// request location permission at runtime.
void requestLocationPermission() async {
PermissionStatus permission =
await LocationPermissions().requestPermissions();
print('permissions: $permission');
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Trust Location Plugin'),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Center(
child: Column(
children: <Widget>[
Text('Mock Location: $_isMockLocation'),
Text('Latitude: $_latitude, Longitude: $_longitude'),
],
)),
),
),
);
}
}
for more information you can see https://pub.dev/packages/trust_location
github link : https://github.com/wongpiwat/trust-location
I think better to use safe_device. It's working on both Android and IOS

Is there any way to open link that comes from onesignal on webview?

I'm using webview widget in my flutter app I want to open a link when user tap on notification, the link comes from additional data on one signal
I tried to make this but it doesn't work
my code :
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:onesignal/onesignal.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _debugLabelString = "";
String url = "https://www.google.com";
#override
void initState() {
super.initState();
initPlatformState();
}
Future<void> initPlatformState() async {
if (!mounted) return;
OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);
OneSignal.shared.setRequiresUserPrivacyConsent(_requireConsent);
var settings = {
OSiOSSettings.autoPrompt: false,
OSiOSSettings.promptBeforeOpeningPushUrl: true
};
OneSignal.shared.setNotificationReceivedHandler((notification) {
this.setState(() {
url = notification.payload.additionalData['url'].toString() ;
});
});
OneSignal.shared
.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
this.setState(() {
// the value of result.notification.payload.additionalData['url'] =
// https://www.facebook.com/
url = result.notification.payload.additionalData['url'].toString() ;
});
});
// NOTE: Replace with your own app ID from https://www.onesignal.com
await OneSignal.shared
.init("086d22bd-5539-4849-9db2-01589fd3429d", iOSSettings: settings);
OneSignal.shared
.setInFocusDisplayType(OSNotificationDisplayType.notification);
}
#override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
appBar: new AppBar(
title: const Text('OneSignal Flutter Demo'),
backgroundColor: Color.fromARGB(255, 212, 86, 83),
),
body: WebviewScaffold(
url: url,
withJavascript: true,
)
),
);
}
}
I put facebook.com on in additional data it show google page not facebook how to make it show the save value the I put on additional data
The setNotificationReceivedHandler creates the callback for when a notification is received on the device in the foreground.
For the "on notification open" callback (which works for if it is in the background), use the setNotificationOpened handler.
Flutter event handler reference.
If you're looking to handle this in the background regardless of whether the notification is opened or not, see Background Notifications (note: be prepared to write native code, here)