Is it possible to get full list of installed application on phone?
I've added to my manifest (but QUERY_ALL_PACKAGES is underlined in red)
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
I've also added:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if(context?.packageManager?.canRequestPackageInstalls() == true) {
val list = context?.packageManager?.getInstalledApplications(PackageManager.GET_META_DATA)
if(list != null) {
list.forEach {
Log.d("test list", it.packageName.toString())
}
} else {
Log.d("test", "list is null" )
}
} else {
Log.d("test", "can not request")
}
}
But every time I get can not request.
TargetSdk for my app is set on 32.
I know about changes in Android 11 so my question is it still possible?
Related
How to detect that the phone has fingerprint hardware or not. I want a code that detects the fingerprint hardware.
I used this code but this code is showing an error on "isHardwareDetected()" this method.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//Fingerprint API only available on from Android 6.0 (M)
FingerprintManager fingerprintManager = (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
if (!fingerprintManager.isHardwareDetected()) {
// Device doesn't support fingerprint authentication
} else if (!fingerprintManager.hasEnrolledFingerprints()) {
// User hasn't enrolled any fingerprints to authenticate with
} else {
// Everything is ready for fingerprint authentication
}
}
I made a minor change in the question code and now it is working fine.
But that class "FingerprintManagerCompat" is deprecated
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val manager = FingerprintManagerCompat.from(this)
if (!manager.isHardwareDetected) {
Log.e("tag","Fingerprint hardware not detected.")
} else if (!manager.hasEnrolledFingerprints()) {
Log.e("tag","No fingerprint is set")
} else {
Log.e("tag","Fingerprint is set")
}
}
Add the following code inside AndroidManifest.xml :
<uses-feature android:name="android.hardware.fingerprint" android:required="true" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
Use this where you require to detect the hardware:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
if (!fingerprintManager.isHardwareDetected()) {
Toast.makeText(getApplicationContext(), "Your device doesn't support fingerprint authentication", Toast.LENGTH_SHORT).show();
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "Please enable the fingerprint permission", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.USE_FINGERPRINT}, FingerprintHandler.FINGERPRINT_PERMISSION);
}
if (!fingerprintManager.hasEnrolledFingerprints()) {
Toast.makeText(getApplicationContext(), "Your Device has no registered Fingerprints! Please register atleast one in your Device settings", Toast.LENGTH_LONG).show();
}
}
In Android Q and above (API >= 29), the WifiManager.disconnect() method has been deprecated.
What would be the solution to disconnect from the Wi-Fi network in Android 10 and above?
I have implemented the next code, yet it fails always returning:
STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID.
I guess the reason for the failure could be that removeNetworkSuggestions maybe is expected to work in conjunction with addNetworkSuggestions, but I don't need to add any networks, on the contrary, to disconnect from the active one.
public final class WifiUtils {
private static final String TAG = "WifiUtils";
public static void disconnect(final Context context) {
// Sanity check
if (context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED) {
// Without the <Fine location> permission the returned SSID is always: '<unknown ssid>'.
// Note: The <Coarse location> permission is not enough.
Log.e(WifiUtils.TAG, "Missing <ACCESS_FINE_LOCATION> permission. Required to obtain the Wifi SSID.");
return;
}
final WifiManager manager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
if (!manager.isWifiEnabled())
return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
final WifiInfo wifiInfo = manager.getConnectionInfo();
if (wifiInfo == null) {
Log.w(WifiUtils.TAG, "Failed to get connection details.");
return;
}
final String ssid = wifiInfo.getSSID();
if (TextUtils.isEmpty(ssid)) {
Log.e(WifiUtils.TAG, "Unable to resolve Wifi SSID.");
} else {
Log.i(WifiUtils.TAG, "Resolved Wifi SSID: " + ssid);
final List<WifiNetworkSuggestion> suggestions = new ArrayList<>();
suggestions.add(new WifiNetworkSuggestion.Builder()
.setSsid(wifiInfo.getSSID())
.build());
final int status = manager.removeNetworkSuggestions(suggestions);
Log.d(WifiUtils.TAG, "Wifi disconnection status result: " + status);
}
} else {
manager.disconnect();
}
}
}
I have the required permissions in the manifest, granted at runtime:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I struggled with this for a while. Best thing to do is have the Android System take care of it with the following intent.
startActivity(new Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY));
This will show a number of WiFi SSIDs around the user's location and they are able to pick one of the WiFis to connect to.
I'am developping an android app with Kotlin, i use the api 28.
I want to get the deviceId number.At the begining i use TelephonyManager.deviceId, after some research,i found that it's deprecated.
I found as solution, replace deviceId by getImei()
The following an excerpt from my code:
val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
if (telephonyManager != null) {
val androidID = Settings.Secure.getString(this.contentResolver, Settings.Secure.ANDROID_ID)
if (androidID != null) {
Utility().DEVICE_ID = androidID
Utility().setDataBykeyValue(applicationContext, AppController.SHAIRD_PREF_DEVICE_ID, androidID)
} else {
val devId = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) telephonyManager.getImei()
else telephonyManager.getDeviceId()
Utility().DEVICE_ID = devId
Utility().setDataBykeyValue(applicationContext, AppController.SHAIRD_PREF_DEVICE_ID, devId)
}
Utility().CARRIER = telephonyManager.simOperatorName
}
Also i add this permission to my AndroidManifest.xml :
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
the "telephonyManager.getImei()" is underline with a red line, and the following msg appear :
Call requires permission which may be rejected by user: code should
explicitly check to see if permission is available (with
checkPermission) or explicitly handle a potential
I want to know what's the problem and how can i correct it
For Java:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
} else {
// else for if they have already given permission
}
}
You can check this tutorial also: https://www.androidhive.info/2016/11/android-working-marshmallow-m-runtime-permissions/
For Kotlin:
val permission = ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_PHONE_STATE), 1)
}
You can check this tutorial also: https://www.techotopia.com/index.php/Kotlin_-_Making_Runtime_Permission_Requests_in_Android
public static String getImei(TelephonyManager tm) {
String imei;
try{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
imei = tm.getDeviceId(0);
}else{
imei = tm.getDeviceId();
}
}catch(SecurityException e){
imei = "";
}
return imei;
}
I am trying to use a simple Flutter plugin (speech recognition wrapper) and have no idea how to request the appropriate permissions on Android 23 or newer. In the Dart part I have:
Future requestPermissions() =>
_channel.invokeMethod("speech.requestPermissions");
In the Android part:
public class SpeechRecognitionPlugin implements MethodCallHandler, RecognitionListener,
PluginRegistry.RequestPermissionResultListener {
Plugin registration:
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "speech_recognition");
SpeechRecognitionPlugin speechRecognitionPlugin = new
SpeechRecognitionPlugin(registrar.activity(), channel);
channel.setMethodCallHandler(speechRecognitionPlugin);
registrar.addRequestPermissionResultListener(speechRecognitionPlugin);
}
Method call:
else if (call.method.equals("speech.requestPermissions")) {
Log.d(LOG_TAG, "speech.requestPermissions");
if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.RECORD_AUDIO)) {
Toast.makeText(activity.getApplicationContext(), "This application needs the Record Audio permission for recognition to work", Toast.LENGTH_LONG).show();
} else {
Log.d(LOG_TAG, "Requesting permissions");
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.RECORD_AUDIO},
1);
}
result.success(hasRecordAudioPermission());
Result callback:
#Override
public boolean onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
boolean granted = false;
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
granted = true;
}
speechChannel.invokeMethod("speech.onPermission", granted);
return true;
}
}
return false;
}
From logcat I see that the "speech.requestPermissions" call happens, but standard Android system permission request is not shown, just this in the logcat may be related:
D/ViewRootImpl(21171): #1 mView = android.widget.LinearLayout{64f050b
V.E...... ......I. 0,0-0,0 #102039d android:id/toast_layout_root}
D/ViewRootImpl(21171): MSG_RESIZED_REPORT: ci=Rect(0, 0 - 0, 0) vi=Rect(0, 0 - 0, 0) or=1
D/ViewRootImpl(21171): #3 mView = null
What is the correct way to request permissions for Flutter plugins?
EDIT: This does not apply to the first run, when the dialog shows correctly, but to subsequent runs when the user did not grant the permission at first or revoked it via settings. I realize that changes the question significantly (making it appear as edge case), but Android permissions are not supposed to work that way.
EDIT: The permissions are present in AndroidManifest.xml
Use Permission plugin for flutter
Request permission
import 'package:permissions_plugin/permissions_plugin.dart';
Map<Permission, PermissionState> permission = await PermissionsPlugin
.requestPermissions([
Permission.ACCESS_FINE_LOCATION,
Permission.ACCESS_COARSE_LOCATION,
Permission.READ_PHONE_STATE
]);
Check status permission
import 'package:permissions_plugin/permissions_plugin.dart';
Map<Permission, PermissionState> permission = await PermissionsPlugin
.checkPermissions([
Permission.ACCESS_FINE_LOCATION,
Permission.ACCESS_COARSE_LOCATION,
Permission.READ_PHONE_STATE
]);
I have this working for location permissions. The only thing I'm doing differently is in your method call here:
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.RECORD_AUDIO},
1);
Instead of using 'ActivityCompat' I store the registrar in a local final variable and I'm doing the following :
registrar.activity().requestPermissions(activity,
new String[]{Manifest.permission.RECORD_AUDIO},
1);
EDIT: Also make sure that you have included the relevant permissions in your AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Add this -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- Flutter stuff --->
</manifest>
Let's say you want to request camera permission using permission_handler package.
In pubspec.yaml file:
permission_handler: ^8.0.0+2
(For Android) Add the permission to android/app/src/main/AndroidManifest.xml file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
...
</manifest>
(For iOS),
(i) Add this to your info.plist file
<key>NSCameraUsageDescription</key>
<string>App needs camera permission to work</string>
(ii) Add 'PERMISSION_CAMERA=1' to your Podfile.
post_install do |installer|
installer.pods_project.targets.each do |target|
flutter_additional_ios_build_settings(target)
target.build_configurations.each do |config|
config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
'$(inherited)',
## Add the following line.
'PERMISSION_CAMERA=1'
]
end
end
end
Request the permission:
final status = await Permission.camera.request();
if (status == PermissionStatus.granted) {
print('Permission granted');
} else if (status == PermissionStatus.denied) {
print('Permission denied. Show a dialog and again ask for the permission');
} else if (status == PermissionStatus.permanentlyDenied) {
print('Take the user to the settings page.');
await openAppSettings();
}
Below android 6.0 its working perfect, but in android marshmallow HDMI status is not coming
private boolean isHdmiSwitchSet() {
File switchFile = new File("/sys/devices/virtual/switch/hdmi/state");
if (!switchFile.exists()) {
switchFile = new File("/sys/class/switch/hdmi/state");
}
try {
Scanner switchFileScanner = new Scanner(switchFile);
Toast.makeText(MainActivity.this,"HDMI Status"+switchFileScanner.nextInt(),Toast.LENGTH_LONG).show();
int switchValue = switchFileScanner.nextInt();
switchFileScanner.close();
return switchValue > 0;
} catch (Exception e) {
return false;
}
}
Follow below steps,
First, Put storage permission in AndroidManifest file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Second, Before access file check permission allowed by user or not:
public boolean checkPermissionForWRITE_STORAGE(){
int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
Third, do your task on true condition.
I found solution,If we will compile like android system application with android:sharedUserId="android.uid.system" its working perfect...
Thank U.