Related
Just an example, I can get the Display Timeout setting like this:
int timeout = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT);
I can set the Display Timeout setting like this:
Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 10000);
How can I programmatically get and set the Fast Charging and the Super Fast Charging settings?
Edit: Thanks to Veniamin for helping me get the correct variable names, here's what worked for me:
try {
int isSuperFastChargingEnabled = Settings.System.getInt(getContentResolver(), "super_fast_charging");
if ( isSuperFastChargingEnabled == 0) {
Settings.System.putInt(getContentResolver(), "super_fast_charging", 1);
Settings.System.putInt(getContentResolver(), "adaptive_fast_charging", 1);
Toast.makeText(this, "Fast charge is set to 1",Toast.LENGTH_LONG).show();
} else if ( isSuperFastChargingEnabled == 1) {
Settings.System.putInt(getContentResolver(), "super_fast_charging", 0);
Settings.System.putInt(getContentResolver(), "adaptive_fast_charging", 0);
Toast.makeText(this, "Fast charge is set to 0",Toast.LENGTH_LONG).show();
}
} catch (Settings.SettingNotFoundException e) {
Toast.makeText(this,"Failed to get fast charge setting",Toast.LENGTH_LONG).show();
}
You can read and update these settings in the Device Care Samsung system application, so I reverse engineered it.
Here is how you can read Fast Charging, Super Fast Charging, and Fast Wireless Charging settings in your application:
val isSuperFastChargingEnabled = Settings.System.getInt(context.contentResolver, "super_fast_charging", 0) == 1
val isFastChargingEnabled = Settings.System.getInt(context.contentResolver, "adaptive_fast_charging", 0) == 1
val isFastWirelessChargingEnabled = Settings.System.getInt(context.contentResolver, "wireless_fast_charging", 0) == 1
Unfortunately, to update these settings programmatically, you need the android.permission.WRITE_SETTINGS permission is only granted to the system applications.
So, if you are not developing a system app, the only way to enable these settings is to ask users to enable them manually. To simplify workflow, you can route users directly to the system Fast Charging Settings Activity, like so:
val intent = Intent()
intent.component = ComponentName(
"com.samsung.android.lool",
"com.samsung.android.sm.battery.ui.BatteryAdvancedMenuActivity"
)
// Activity class name may be updated in future versions, so
// the safest way to handle Activity class name updates is to wrap this
// call in the try/catch and add a custom error handling if the activity wasn't found.
try {
startActivity(intent)
} catch (e: Exception) {
// Custom error handling
}
Since these settings are vendor-specific, checking the vendor id before reading them is recommended.
I tested it and confirm that it works on the Samsung Galaxy S20 (SM-G980F/DS); Android 12; One UI 4.1.
I work with camera2API on Samsung S5 and if i try get state of focus i get value 0 which is equals to CaptureResult.CONTROL_AF_STATE_INACTIVE...
There is snip of code :
private void process(CaptureResult result) {
switch (mState) {
case CameraHelper.STATE_PREVIEW: {
// We have nothing to do when the camera preview is working normally.
here i get ---> Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
if (CaptureResult.CONTROL_AF_TRIGGER_START == afState) {
if (areWeFocused) {
Log.e("---!!! HERE !!!--- :", String.valueOf(areWeFocused));
}else {
}
}
if (CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED == afState) {
areWeFocused = true;
} else {
areWeFocused = false;
}
break;
}
But i also tried to test it on my Meizu MX5 and i get 1 - CaptureResult.CONTROL_AF_TRIGGER_START or 2 - CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED
Question is : what is the difference in my code? Why do i get 0 in one case and 1 or 2 in another?
I know this is an old question, but i just ran into the same issue. Read through the Android docs about ControlAfState (AF = Auto Focus for those who are unaware, like I was). If AutoFocus Mode (afMode) is set to AF_MODE_OFF you will get the ControlAfState of Inactive.
Android CaptureResult.CONTROL_AF_STATE
With the following, the first time it's called it works, but then fails on subsequent calls with "FirebaseApp name [DEFAULT] already exists!"
public FirebaseDatabase conn(Context c) {
FirebaseOptions options = new FirebaseOptions.Builder()
.setApiKey("key")
.setDatabaseUrl("url")
.setApplicationId("ID")
.build();
/////I tried Try and Catch with no success//////
FirebaseApp app = FirebaseApp.initializeApp(c, options);
/// for this : FirebaseApp app = FirebaseApp.initializeApp(c, options, "some_app");
//// will fail with "FirebaseApp name some_app already exists!"
return FirebaseDatabase.getInstance(app);
}
All of the above is an attempt to connect to a second Firebase App.
On firebase web, you check if already initialized with:
if (firebase.apps.length === 0) {
firebase.initializeApp({});
}
In v9, Firebase has been modularized for better tree shaking. So we can no longer import entire app and check the apps property AFAIK. The below approach can be used instead.
import { initializeApp, getApps, getApp } from "firebase/app";
getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();
https://firebase.google.com/docs/reference/js/v9/app.md#getapps for documentation
Firebase Version 9
import { initializeApp, getApp } from "firebase/app";
const createFirebaseApp = (config = {}) => {
try {
return getApp();
} catch () {
return initializeApp(config);
}
};
const firebaseApp = createFirebaseApp({/* your config */})
For those wondering how to do the same as the accepted answer, in Android:
if (FirebaseApp.getApps(context).isEmpty()) {
FirebaseApp.initializeApp(context);
}
and in an instrumented test environment, use this context:
InstrumentationRegistry.getContext()
You can try to get the Firebase app instance, in it's code firebase checks if it's initialized, if not it throws an IllegalStateException.
try{
FirebaseApp.getInstance();
}
catch (IllegalStateException e)
{
//Firebase not initialized automatically, do it manually
FirebaseApp.initializeApp(this);
}
I think what you want to do is check the list of running apps before initializing your app. Each of the SDKs have a method for getting this array, in android it's getApps:
https://firebase.google.com/docs/reference/android/com/google/firebase/FirebaseApp.html
Then you can check to see if your app is already initialized.
In my case I just ended up checking the length of the array (I'm using the javascript / web sdk so I'm sure it's a little different for Android) and initializing a new app if it is 0.
In firebase admin SDK for java, initialize the app if and only if there is no app.
if (FirebaseApp.getApps().isEmpty()) {
FirebaseApp.initializeApp();
}
I faced the similar issue.
I solved the following problem by deleting the already initialized app.
// Access your firebase app
let app = firebase.app();
// Delete your app.
app.delete(app);
Solution works for web.
Not sure in android, but how about using a singleton method. In JS you can do this. Hope this helps someone
// Config file
import * as firebase from "firebase";
const config = {...};
export default !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();
// Other file
import firebase from '../firebase';
import * as firebase from "firebase/app";
firebase.apps.map(e => e.name); // Give you an array of initialized apps
For those who are using dotNet FirebaseAdmin SDK
if (FirebaseApp.GetInstance("[DEFAULT]") == null)
{
var createdApp = FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("private-key.json")
});
}
I faced the similar issue, I resolved it as following:
Create a var for the application and initialize it with null
Take reference of the application while initialization
Check before initializing it again
//global variable
var firebaseResumeDownloadAdd = null;
//inside function check before initializing
if(firebaseResumeDownloadAdd==null){
firebaseResumeDownloadAdd =
firebase.initializeApp(functions.config().firebase);
}
in Android, depending on Daniel Laurindo's answer:
if (FirebaseApp.getApps(context).size != 0) {
}
A cleaner solution for ES6+ is
if (!firebase.apps.length) {
...
}
Simple use Java 8 Stream and Optional featured.
Code below as
FirebaseApp.getApps()
.stream()
.filter(firebaseApp ->
firebaseApp.getName().equals("APP_NAME"))
.findFirst()
.orElseGet(() -> FirebaseApp.initializeApp(firebaseOptions, "APP_NAME"));
Th
Use Platform check to initialize according to environment
On firebase web, you check if already initialized with
use the below snippet while launching MYAPP()
import 'dart:io';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isAndroid || Platform.isIOS) {
await Firebase.initializeApp();
} else {
if (Firebase.apps.isEmpty) {
await Firebase.initializeApp(
// connect for web to firebase
options:firebaseOptions
}
}
runApp(const MyApp());
}
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
For web, you could use:
import { getApp, initializeApp } from "firebase/app"
const firebaseConfig = {/* YOUR CONFIG */}
function createFirebaseApp(config) {
try {
return getApp()
} catch {
return initializeApp(config)
}
}
const firebaseApp = createFirebaseApp(firebaseConfig)
As of now, I Do not have access to comments or likes. But I think this point is important to make.
Many good answers here, but it is also essential to talk about the best answers and performance.
Ideally, you want to minimize code that goes into your production and also want to make sure that there are no unnecessary pieces out there. Thus, a tree-shaking solution is best.
I do following
import { initializeApp, getApps, cert } from "firebase-admin/app";
const secret = JSON.parse(process.env.FIREBASE_SECRET || "{}");
if (!getApps().length) initializeApp({ credential: cert(secret) });
If you are using Nativescript to build an hybrid mobile app for Android | iOS you can use this script:
import * as firebase from 'nativescript-plugin-firebase';
_initFirebase(): Promise<any> {
if (!(firebase as any).initialized) {
return firebase.init({}).then(
() => {
console.info('firebase started...');
},
(error) => console.error(error)
);
}
}
This question already has answers here:
How do I programmatically determine operating system in Java?
(22 answers)
Closed 3 years ago.
I have an app that runs on several mobile devices running either Fedora or Android. To consolidate my codebase and distribution I would like to determine which OS I am on. I tried System.getProperty("os.name"), but that just returns "Linux". Is there something unique to Android in the System properties?
Thanks
There are several properties you could check. Candidates are:
java.vendor.url --> http://www.android.com
java.vm.name --> Dalvik (I don't know, which one Fedora is using...)
java.vm.vendor --> The Android Project
java.vendor --> The Android Project
Maybe you want to check by yourself?
Properties p = System.getProperties();
Enumeration keys = p.keys();
while(keys.hasMoreElements()) {
String key = (String) keys.nextElement();
String value = (String) p.get(key);
System.out.println(key + " >>>> " + value);
}
I do not know Android but if you do not find some unique system property you can sometimes identify the system if some specific class exists there. So you can do the following:
boolean isAndroid() {
try {
Class.forName("the class name");
return true;
} catch(ClassNotFoundException e) {
return false;
}
}
Here is some code that I wrote using the information from this page, in case you want to copy-paste:
private static YLogger ylogger;
public static YLogger getLogger() {
if (ylogger == null){
// need to find a new logger. Let's check if we have Android running
if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")){
ylogger = new AndroidLogger();
ylogger.d("YLoggerFactory", "Instantiating Android-based logger");
} else {
// fallback option, system logger.
ylogger = new SystemLogger();
ylogger.d("YLoggerFactory", "Instantiating System-based logger");
}
}
return ylogger;
}
The list of defined system properties is here: https://developer.android.com/reference/java/lang/System#getProperties()
I'm using
boolean android = "The Android Project".equals(System.getProperty("java.specification.vendor"));
I use this in my processing sketch to determine in which mode I'm running i.e. where I'm running it.
enum Mode {
java, android
}
Mode getMode() {
return System.getProperty("java.runtime.name").equals("Android Runtime") ? Mode.android : Mode.java;
}
if (getMode() == Mode.java){
// do something
// eg: do something that android can't handle
} else {
// do android stuff
// eg: scale the sketch by 2 to improve visibility
}
How to get Android device name? I am using HTC desire. When I connected it via HTC Sync the software is displaying the Name 'HTC Smith' . I would like to fetch this name via code.
How is this possible in Android?
In order to get Android device name you have to add only a single line of code:
android.os.Build.MODEL;
Found here: getting-android-device-name
You can see answers at here Get Android Phone Model Programmatically
public String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
} else {
return capitalize(manufacturer) + " " + model;
}
}
private String capitalize(String s) {
if (s == null || s.length() == 0) {
return "";
}
char first = s.charAt(0);
if (Character.isUpperCase(first)) {
return s;
} else {
return Character.toUpperCase(first) + s.substring(1);
}
}
I solved this by getting the Bluetooth name, but not from the BluetoothAdapter (that needs Bluetooth permission).
Here's the code:
Settings.Secure.getString(getContentResolver(), "bluetooth_name");
No extra permissions needed.
On many popular devices the market name of the device is not available. For example, on the Samsung Galaxy S6 the value of Build.MODEL could be "SM-G920F", "SM-G920I", or "SM-G920W8".
I created a small library that gets the market (consumer friendly) name of a device. It gets the correct name for over 10,000 devices and is constantly updated. If you wish to use my library click the link below:
AndroidDeviceNames Library on Github
If you do not want to use the library above, then this is the best solution for getting a consumer friendly device name:
/** Returns the consumer friendly device name */
public static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return capitalize(model);
}
return capitalize(manufacturer) + " " + model;
}
private static String capitalize(String str) {
if (TextUtils.isEmpty(str)) {
return str;
}
char[] arr = str.toCharArray();
boolean capitalizeNext = true;
String phrase = "";
for (char c : arr) {
if (capitalizeNext && Character.isLetter(c)) {
phrase += Character.toUpperCase(c);
capitalizeNext = false;
continue;
} else if (Character.isWhitespace(c)) {
capitalizeNext = true;
}
phrase += c;
}
return phrase;
}
Example from my Verizon HTC One M8:
// using method from above
System.out.println(getDeviceName());
// Using https://github.com/jaredrummler/AndroidDeviceNames
System.out.println(DeviceName.getDeviceName());
Result:
HTC6525LVW
HTC One (M8)
Try it. You can get Device Name through Bluetooth.
Hope it will help you
public String getPhoneName() {
BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
String deviceName = myDevice.getName();
return deviceName;
}
You can use:
From android doc:
MANUFACTURER:
String MANUFACTURER
The manufacturer of the product/hardware.
MODEL:
String MODEL
The end-user-visible name for the end product.
DEVICE:
String DEVICE
The name of the industrial design.
As a example:
String deviceName = android.os.Build.MANUFACTURER + " " + android.os.Build.MODEL;
//to add to textview
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(deviceName);
Furthermore, their is lot of attribute in Build class that you can use, like:
os.android.Build.BOARD
os.android.Build.BRAND
os.android.Build.BOOTLOADER
os.android.Build.DISPLAY
os.android.Build.CPU_ABI
os.android.Build.PRODUCT
os.android.Build.HARDWARE
os.android.Build.ID
Also their is other ways you can get device name without using Build class(through the bluetooth).
Following works for me.
String deviceName = Settings.Global.getString(.getContentResolver(), Settings.Global.DEVICE_NAME);
I don't think so its duplicate answer. The above ppl are talking about Setting Secure, for me setting secure is giving null, if i use setting global it works. Thanks anyways.
universal way to get user defined DeviceName working for almost all devices and not requiring any permissions
String userDeviceName = Settings.Global.getString(getContentResolver(), Settings.Global.DEVICE_NAME);
if(userDeviceName == null)
userDeviceName = Settings.Secure.getString(getContentResolver(), "bluetooth_name");
Try this code. You get android device name.
public static String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
if (model.startsWith(manufacturer)) {
return model;
}
return manufacturer + " " + model;
}
#hbhakhra's answer will do.
If you're interested in detailed explanation, it is useful to look into Android Compatibility Definition Document. (3.2.2 Build Parameters)
You will find:
DEVICE - A value chosen by the device implementer containing the
development name or code name identifying the configuration of the
hardware features and industrial design of the device. The value of
this field MUST be encodable as 7-bit ASCII and match the regular
expression “^[a-zA-Z0-9_-]+$”.
MODEL - A value chosen by the device implementer containing the name
of the device as known to the end user. This SHOULD be the same name
under which the device is marketed and sold to end users. There are no
requirements on the specific format of this field, except that it MUST
NOT be null or the empty string ("").
MANUFACTURER - The trade name of the Original Equipment Manufacturer
(OEM) of the product. There are no requirements on the specific format
of this field, except that it MUST NOT be null or the empty string
("").
UPDATE
You could retrieve the device from buildprop easitly.
static String GetDeviceName() {
Process p;
String propvalue = "";
try {
p = new ProcessBuilder("/system/bin/getprop", "ro.semc.product.name").redirectErrorStream(true).start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
propvalue = line;
}
p.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return propvalue;
}
But keep in mind, this doesn't work on some devices.
Simply use
BluetoothAdapter.getDefaultAdapter().getName()
static String getDeviceName() {
try {
Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
Method getMethod = systemPropertiesClass.getMethod("get", String.class);
Object object = new Object();
Object obj = getMethod.invoke(object, "ro.product.device");
return (obj == null ? "" : (String) obj);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
you can get 'idol3' by this way.
Tried These libraries but nothing worked according to my expectation and was giving absolutely wrong names.
So i created this library myself using the same data.
Here is the link
AndroidPhoneNamesFinder
To use this library just add this for implementation
implementation 'com.github.aishik212:AndroidPhoneNamesFinder:v1.0.2'
Then use the following kotlin code
DeviceNameFinder.getPhoneValues(this, object : DeviceDetailsListener
{
override fun details(doQuery: DeviceDetailsModel?)
{
super.details(doQuery)
Log.d(TAG, "details: "+doQuery?.calculatedName)
}
})
These are the values you will get from DeviceDetailsModel
val brand: String? #This is the brandName of the Device
val commonName: String?, #This is the most common Name of the Device
val codeName: String?, #This is the codeName of the Device
val modelName: String?, #This is the another uncommon Name of the Device
val calculatedName: String?, #This is the special name that this library tries to create from the above data.
Example of Android Emulator -
brand=Google
commonName=Google Android Emulator
codeName=generic_x86_arm
modelName=sdk_gphone_x86
calculatedName=Google Android Emulator
Within the GNU/Linux environment of Android, e.g., via Termux UNIX shell on a non-root device, it's available through the /system/bin/getprop command, whereas the meaning of each value is explained in Build.java within Android (also at googlesource):
% /system/bin/getprop | fgrep ro.product | tail -3
[ro.product.manufacturer]: [Google]
[ro.product.model]: [Pixel 2 XL]
[ro.product.name]: [taimen]
% /system/bin/getprop ro.product.model
Pixel 2 XL
% /system/bin/getprop ro.product.model | tr ' ' _
Pixel_2_XL
For example, it can be set as the pane_title for the status-right within tmux like so:
tmux select-pane -T "$(getprop ro.product.model)"
Gets an Android system property, or lists them all
adb shell getprop >prop_list.txt
Find your device name in prop_list.txt to get the prop name
e.g. my device name is ro.oppo.market.name
Get oppo.market Operator
adb shell getprop ro.oppo.market.name
My case on windows as follows
D:\winusr\adbl
λ *adb shell getprop ro.oppo.market.name*
OPPO R17