How to get android mobile IMEI number using Dart language in Flutter? - flutter

I need to get android mobile IMEI number using Dart language in Flutter. How to get this slot1 or slot2 IMEI number from Android mobiles.

You could use device_information package. For this package to use you need to ask for phone permission from the user. So add the below permission in your Manifest file.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
The second step is to get the user's permission to access their phone's info. Check the below code for permission:
Future<String> _askingPhonePermission() async {
final PermissionStatus permissionStatus = await _getPhonePermission();
}
Future<PermissionStatus> _getPhonePermission() async {
final PermissionStatus permission = await Permission.phone.status;
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.denied) {
final Map<Permission, PermissionStatus> permissionStatus =
await [Permission.phone].request();
return permissionStatus[Permission.phone] ??
PermissionStatus.undetermined;
} else {
return permission;
}
}
And finally, use the above-mentioned package to extract the device's IMEI number.
String imeiNo = await DeviceInformation.deviceIMEINumber;

Related

Find Address From Coordinates

final addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
selectedAddress = addresses.first;
The plugin geocoder uses a deprecated version of the Android embedding.
To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.
If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.
Use [geolocator][1] package and write the below code to get the city name and coordinates
void main() async {
await configureInjection(Environment.dev);
WidgetsFlutterBinding.ensureInitialized();
Position _currentPosition = await getCurrentPosition();
List<Placemark> placemarks = await placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = placemarks[0];
runApp(AppWidget());
}
Future<Position> getCurrentPosition() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
);
}

Flutter Error: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord

I needed to import contacts from mobile, and I used contacts_service from pub.dev. Then I made the changes required in AndroidManifest.xml for android and in info.plist for iOS, i.e, added the required permission, still I am getting this error when I am trying to read contacts from phone.
Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord
I resolved this issue, by requesting permission from the user, like this,
#override
void initState() {
super.initState();
getContacts();
}
// Function to get permission from the user
_contactsPermissions() async {
PermissionStatus permission = await Permission.contacts.status;
if (permission != PermissionStatus.granted && permission != PermissionStatus.denied) {
Map<Permission, PermissionStatus> permissionStatus = await [Permission.contacts].request();
return permissionStatus[Permission.contacts] ?? PermissionStatus.undetermined;
} else {
return permission;
}
}
//Function to import contacts
getContacts() async {
PermissionStatus contactsPermissionsStatus = await _contactsPermissions();
if (contactsPermissionsStatus == PermissionStatus.granted) {
List<Contact> _contacts = (await ContactsService.getContacts(withThumbnails: false)).toList();
setState(() {
contacts = _contacts;
});
}
}

Permission request in Flutter

How can I request permission for accessing the device microphone for recording audio in Flutter?
I have tried looking this up but haven't been able to find a clear answer.
You could do something like this:
await _askingPermission();
Future<String> _askingPermission() async {
final PermissionStatus permissionStatus =
await _getPhonePermission();
if (permissionStatus == PermissionStatus.granted){
//permission is granted
} else{
//permission denied or undermined
}
}
Future<PermissionStatus> _getPermission() async {
final PermissionStatus permission = await Permission.microphone.status;
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.denied) {
final Map<Permission, PermissionStatus> permissionStatus =
await [Permission.microphone].request();
return permissionStatus[Permission.microphone] ??
PermissionStatus.undetermined;
} else {
return permission;
}
}
Add this line in your manifest file
<uses-permission android:name="android.permission.RECORD_AUDIO" />

Unhandled Exception: PlatformException(PERMISSION_DENIED, Access to location data denied, null)

it give the exception when i get the current location of the user . my flutter version :-
v1.17.4, and my info.plist code is given below. geolocator: ^5.3.2+2
Future<Position> locateUser() async {
return await Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.low,locationPermissionLevel:
GeolocationPermission.location);
}
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to location when open.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to location when in the background.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access to location when open and in the background.</string>
It might be late to reply but I was also facing the same problem where the app was not asking for permission in iOS and was working perfectly fine in android.
Because it was not asked for permission that's why the permission code was not working for iOS. I found a package named "location_permissions" which can be used to ask for permission manually.
Steps to do are following
Add "location_permissions: 3.0.0+1" this dependencies in "pubspec.yaml". Please note that I did that for flutter 1.22.0 so for flutter 2.0 this might be an issue.
Import the package in the file
import 'package:location_permissions/location_permissions.dart';
Add the following code on the page where you want to ask for permission. (Better to add that on the very first page of your app.)
#override
void initState() {
....
if (Platform.isIOS) {
location_permission();
}
....
}
Add the following two methods in the same file
void location_permission() async {
final PermissionStatus permission = await _getLocationPermission();
if (permission == PermissionStatus.granted) {
final position = await geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
// Use the position to do whatever...
}
}
Future<PermissionStatus> _getLocationPermission() async {
final PermissionStatus permission = await LocationPermissions()
.checkPermissionStatus(level: LocationPermissionLevel.location);
if (permission != PermissionStatus.granted) {
final PermissionStatus permissionStatus = await LocationPermissions()
.requestPermissions(
permissionLevel: LocationPermissionLevel.location);
return permissionStatus;
} else {
return permission;
}
}
That's it now you should get a popup in the iOS app which will ask for the permission of location.
I was facing the same issue. I was running on IOS simulator
Issue Resolved on calling requestPermission() method
LocationPermission permission = await Geolocator.requestPermission();
Future<Position> position =
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
In info.plist:
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to your location.</string>
dependency in pubspec.yaml:
geolocator: ^8.0.5

Device Country in Flutter

I am trying to get country of device (Android) in Flutter. I used this tutorial, but I think it is the wrong approach for my problem.
Locale myLocale = Localizations.localeOf(context);
print(myLocale.languageCode.toString() + ' ' + myLocale.countryCode.toString());
Based on this, I have couple of questions/issues:
I am always getting en US even though I have set device language to Urdu - Pakistan. So what am I missing?
I want to display certain app items based on the country the device is in, not based on language as people living in Pakistan with language set to English (US) will get items actually intended for USA based users. So, should I use geoLocation and get longitude and latitude and decide based on that data? Or is there any other simpler approach just to get country of user?
Thanking in anticipation.
Add this 2 library in pubspec.yaml
geolocator: ^5.1.1
geocoder: ^0.2.1
Then Add permission for Location access. Check here
At last call this method where you want.
Future<String> getCountryName() async {
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
debugPrint('location: ${position.latitude}');
final coordinates = new Coordinates(position.latitude, position.longitude);
var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = addresses.first;
return first.countryName; // this will return country name
}
if you are looking to get the device country without using "geolocator" so you don't need to get the device permission, you can use the below code:
Future<String> getCountry() async{
Network n = new Network("http://ip-api.com/json");
locationSTR = (await n.getData());
locationx = jsonDecode(locationSTR);
return locationx["country"];
}
The Network class code is below:
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
class Network {
final String url;
Network(this.url);
Future<String> apiRequest(Map jsonMap) async {
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/x-www-form-urlencoded');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
// todo - you should check the response.statusCode
String reply = await response.transform(utf8.decoder).join();
httpClient.close();
return reply;
}
Future<String> sendData(Map data) async {
http.Response response = await http.post(url,
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(data));
if (response.statusCode == 200)
return (response.body);
else
return 'No Data';
}
Future<String> getData() async {
http.Response response = await http.post(url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'});
if (response.statusCode == 200)
return (response.body);
else
return 'No Data';
}
}
you can get the city and countrycode and internet provider as well.
try this
import 'dart:io' show Platform;
String localeName = Platform.localeName;
Use the flutter_sim_country_code, with this package you can get a user localizations variables and country code directly from the user sim and network provider. For example;
networkCountryIso,
simCountryIso,
these variable always holds the country code,
please use package https://pub.dev/packages/devicelocale
I have tested with real device, it works fine
code snippet
String locale = await Devicelocale.currentLocale;
full code
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:devicelocale/devicelocale.dart';
void main() => runApp(MyApp());
/// Demo getting a device locale
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
List _languages = List();
String _locale;
#override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
List languages;
String currentLocale;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
languages = await Devicelocale.preferredLanguages;
print(languages);
} on PlatformException {
print("Error obtaining preferred languages");
}
try {
currentLocale = await Devicelocale.currentLocale;
print(currentLocale);
} on PlatformException {
print("Error obtaining current locale");
}
// 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(() {
_languages = languages;
_locale = currentLocale;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text("Current locale: "),
Text('$_locale'),
Text("Preferred Languages: "),
Text(_languages.toString()),
],
)
),
),
);
}
}
I had the same problem working on an app with country specific functionality. All these methods mentioned here are good, having gone through them all myself I realised none will cover all possible scenarios.
So, I changed the approach to the problem. Instead of making decision programmatically, which country user is in and going ahead with it. I thought it is better to identify the user's country using one of the methods that suits your app most and then present it to the user. If they wish they can change it, otherwise in most cases auto detection is valid.
For my app I presented users with country when logging in and a flat button at bottom to change it if it is not correct.
This solution requires location service to be enabled.
Add these two dependencies in your pubspec.yaml file
geolocator: ^7.0.3
geocoding: ^2.0.0
Future<String> getCountryCodeName() async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
List<Placemark> address =
await placemarkFromCoordinates(position.latitude, position.longitude);
Placemark placeMark = address.first;
String country = placeMark.country;
return country; // this will return country }
You have to use a geolocator and geocode plugin. then create this method use below code. In Android Manifest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
Function
Future<String> getCountryName() async {
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
await Geolocator.requestPermission();
}
if (permission == LocationPermission.deniedForever) {
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
debugPrint('location: ${position.latitude}');
final coordinates = new Coordinates(position.latitude, position.longitude);
var addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
var first = addresses.first;
print(first.countryName);
return first.countryName;
}
Try this. Don't forget to provide necessary permissions in android manifest and ios as well.
import 'package:geolocator/geolocator.dart';
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
}).catchError((e) {
print(e);
});
Building on #chunhunghan's answer, you can use the plugin https://pub.dev/packages/devicelocale. To get the country code, you have to use:
Locale l = await Devicelocale.currentAsLocale;
String countryCode = l.countryCode;
For the full code, check: https://pub.dev/packages/devicelocale#-example-tab-
var code = WidgetsBinding.instance.window.locale.countryCode;