In order to get the description of a permission. I used the following code:
PackageManager packageManager = this.getPackageManager();
long time = System.currentTimeMillis();
PermissionInfo pinfo = null;
try {
pinfo = packageManager.getPermissionInfo("android.permission.BODY_SENSORS", PackageManager.GET_META_DATA);
if(pinfo != null) Log.i("permissions","pInfo not null???????????????????????????????????????");
Log.i("permissions ", pinfo.loadDescription(packageManager) + " *** " + pinfo.group);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
time = System.currentTimeMillis() - time;
But for some permissions, like- android.permission.BATTERY_STATS, I have a null char sequence when I call pinfo.loadDescription(packageManager). I don't understand why? And I'm trying to find the reason, but no way to get it. Any android expert could please explain it for me?
I have a null CharSequence when I call pinfo.loadDescription(packageManager).I don't understand why?
Because Google elected not to provide a description (or a title) for that permission. This is true for many of the signature-level permissions. You can examine the AOSP edition of the framework manifest to get a sense of what you can expect.
Related
I am trying google drive api to search parents of a folder. In search query i have to pass file id dynamically instead of hard coding. I tried below code. but I am getting file not found json response.
here its not taking fileId as value i think its consider as String
if I hardcode the value it is working.
FileList result = service.files().list().setQ("name='testfile' ").execute();
for (com.google.api.services.drive.model.File file : result.getFiles()) {
System.out.printf("Found file: %s (%s)\n",
file.getName(), file.getId());
String fileId =file.getId();
FileList childern = service.files().list().setQ(" + \"file.getId()\" in parents").setFields("files(id, name, modifiedTime, mimeType)").execute();
This should help.
String fileid=file.getId()
service.files().list().setQ("'" + fileId + "'" + " in parents").setFields("files(id, name, modifiedTime, mimeType)").execute();
Make sure you have valid file.getId()
I know your question states java but the only sample of this working is in C#. Another issue is as far as i know PageStreamer.cs does not have an equivalent in the java client library.
I am hoping that C# and java are close enough that this might give you some ideas of how to get it working in Java. My java knowledge is quote basic but i may be able to help you debug it if you want to try to convert this.
try
{
// Initial validation.
if (service == null)
throw new ArgumentNullException("service");
// Building the initial request.
var request = service.Files.List();
// Applying optional parameters to the request.
request = (FilesResource.ListRequest)SampleHelpers.ApplyOptionalParms(request, optional);
var pageStreamer = new Google.Apis.Requests.PageStreamer<Google.Apis.Drive.v3.Data.File, FilesResource.ListRequest, Google.Apis.Drive.v3.Data.FileList, string>(
(req, token) => request.PageToken = token,
response => response.NextPageToken,
response => response.Files);
var allFiles = new Google.Apis.Drive.v3.Data.FileList();
allFiles.Files = new List<Google.Apis.Drive.v3.Data.File>();
foreach (var result in pageStreamer.Fetch(request))
{
allFiles.Files.Add(result);
}
return allFiles;
}
catch (Exception Ex)
{
throw new Exception("Request Files.List failed.", Ex);
}
Good morning
I was searching for a way to know if an app, given the package name, requests a certain permission and if that permission is granted (via settings). I was looking for something like that:
if(//com.package.name requests Manifest.permission.camera and that permission is granted)
{//do something}
I have already read this thread http://stackoverflow.com/questions/31535088/android-m-programmatically-revoke-permissions but it doesn't find a way to know if an app is actually requesting a certain permission and if it's granted.
Thanks in advance
Regards
Use the following code in your activity:
I created StringBuffer appNameAndPermissions = new StringBuffer(); to append all the apps and permisssions info.
It's working fine. I tested it already. If you have any issues, please let me know.
StringBuffer appNameAndPermissions = new StringBuffer();
PackageManager pm = getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo applicationInfo : packages) {
Log.d("test", "App: " + applicationInfo.name + " Package: " + applicationInfo.packageName);
try {
PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName, PackageManager.GET_PERMISSIONS);
appNameAndPermissions.append(packageInfo.packageName+"*******:\n");
//Get Permissions
String[] requestedPermissions = packageInfo.requestedPermissions;
if(requestedPermissions != null) {
for (int i = 0; i < requestedPermissions.length; i++) {
Log.d("test", requestedPermissions[i]);
appNameAndPermissions.append(requestedPermissions[i]+"\n");
}
appNameAndPermissions.append("\n");
} catch (NameNotFoundException e) {
e.printStackTrace();
}
Use the following permission in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.GET_TASKS"/>
Source and more answers here
I'm trying to get the size occupied by my application package. Every application has one location in the internal/external storage.
I want to calculate the size of the following directory, how can I do that?
I know I can use StorageStateManager on and above Oreo (API 26) devices, but how can I achieve this before oreo devices.
Application Directory : /Android/data/myapplicationpackage
I'm trying to use PackageStats but It's giving me always zero. What's the actual way to use this code?
I used the following code and it gives me all zero.
PackageStats stats = new PackageStats(context.getPackageName());
long codeSize = stats.codeSize + stats.externalCodeSize;
long dataSize = stats.dataSize + stats.externalDataSize;
long cacheSize = stats.cacheSize + stats.externalCacheSize;
long appSize = codeSize + dataSize + cacheSize;
PackageStats stats = new PackageStats(context.getPackageName());
It will only creates the packagestats object. As from the source, the constructor will do initializing the fields,
public PackageStats(String pkgName) {
packageName = pkgName;
userHandle = UserHandle.myUserId();
}
for api<26,
You need to use IPackageStatsObserver.aidl and have to invoke getPackageSizeInfo method by reflection.
PackageManager pm = getPackageManager();
Method getPackageSizeInfo = pm.getClass().getMethod(
"getPackageSizeInfo", String.class, IPackageStatsObserver.class);
getPackageSizeInfo.invoke(pm, "com.yourpackage",
new IPackageStatsObserver.Stub() {
#Override
public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
throws RemoteException {
//here the pStats has all the details of the package
}
});
Here is the complete solution for it. It works great.
from api 26,
The getPackageSizeInfo method is deprecated.
You can use this code,
#SuppressLint("WrongConstant")
final StorageStatsManager storageStatsManager = (StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE);
final StorageManager storageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(packagename, 0);
StorageStats storageStats = storageStatsManager.queryStatsForUid(ai.storageUuid, info.uid);
cacheSize =storageStats.getCacheBytes();
dataSize =storageStats.getDataBytes();
apkSize =storageStats.getAppBytes();
size+=info.cacheSize;
} catch (Exception e) {}
But to use this code, You need USAGE ACCESS PERMISSION .
I have an app, which sets the hardware parameters of the Camera programmatically.
However, as I've been told, and have come to observe, not all chipsets support all parameters.
For example, the Nexus 4 (Qualcomm) has sharpness, and sharpness-max parameters, the Galaxy Note II 3g doesn't have any.
Hence, when I set sharpness parameter, the Nexus responds well, but the Galaxy force closes:
java.lang.RuntimeException: setParameters failed
at android.hardware.Camera.native_setParameters(Native Method)
at android.hardware.Camera.setParameters(Camera.java:1452)
My question is, how can I get the RAW info programmatically? I need to get the parameters, their values, and whether they exist or not.
I wish to get the RAW-Metadata parameters, as like this: database
Alright, thought this would be a fun bit of practice. So, Android does not give a public API into this information. Why? I have no idea. Looks like you can do a Camera.Parameters#get(String) to check for any particular parameter that you're interested in, but lets say you're greedy and want the whole list to yourself. In that case, we can dive in using Reflection, but be aware that there is a strong possibility that this will not work on all versions of Android or may break in future versions. With that said, here's how you do it:
private static Map<String, String> getFullCameraParameters (Camera cam) {
Map<String, String> result = new HashMap<String, String>(64);
final String TAG = "CameraParametersRetrieval";
try {
Class camClass = cam.getClass();
//Internally, Android goes into native code to retrieve this String of values
Method getNativeParams = camClass.getDeclaredMethod("native_getParameters");
getNativeParams.setAccessible(true);
//Boom. Here's the raw String from the hardware
String rawParamsStr = (String) getNativeParams.invoke(cam);
//But let's do better. Here's what Android uses to parse the
//String into a usable Map -- a simple ';' StringSplitter, followed
//by splitting on '='
//
//Taken from Camera.Parameters unflatten() method
TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(';');
splitter.setString(rawParamsStr);
for (String kv : splitter) {
int pos = kv.indexOf('=');
if (pos == -1) {
continue;
}
String k = kv.substring(0, pos);
String v = kv.substring(pos + 1);
result.put(k, v);
}
//And voila, you have a map of ALL supported parameters
return result;
} catch (NoSuchMethodException ex) {
Log.e(TAG, ex.toString());
} catch (IllegalAccessException ex) {
Log.e(TAG, ex.toString());
} catch (InvocationTargetException ex) {
Log.e(TAG, ex.toString());
}
//If there was any error, just return an empty Map
Log.e(TAG, "Unable to retrieve parameters from Camera.");
return result;
}
I've been struggling to get the example running from below:
https://developers.google.com/eclipse/docs/getting_started
The first problem I had was didn't have installed 'Google Cloud Messaging for Android Library' in the Android SDK (obvious I know).
But now I have an issue with the auto-generated code in two files in the Android project:
GCMIntentService.java and RegisterActivity.java
The errors are:
The method getDeviceInfo(String) is undefined for the type Deviceinfoendpoint GCMIntentService.java
The method listMessages() is undefined for the type MessageEndpoint RegisterActivity.java
The method insertDeviceInfo(DeviceInfo) is undefined for the type Deviceinfoendpoint GCMIntentService.java
The method removeDeviceInfo(String) is undefined for the type Deviceinfoendpoint GCMIntentService.java
I'm using Java SDK v1.7.0_15 on Ubuntu but I also tried on Windows 7 with Java SDK v1.6 and had the same issue. Latest Android Platform 4.2.2 and Google App Engine 1.7.7. Eclipse is Juno Service Release 2.
The problem looks like they are doing some casting wrong, because there is a method getDeviceInfo for inner class DeviceInfoEndpoint inside Deviceinfoendpoint (different capatilisations).
I could try and fix it, but just wondering if I have something wrong in my setup for this to be happening?
Any help would be appreciated.
In your GCMIntentService.java class, add .deviceInfoEndpoint() after the endpoint object in the lines with errors as shown below:
DeviceInfo existingInfo = endpoint.getDeviceInfo(registration)
DeviceInfo existingInfo = endpoint.deviceInfoEndpoint().getDeviceInfo(registration)
In RegisterActivity.java change the line
messageEndpoint.listMessages().setLimit(5).execute();
to
messageEndpoint.messageEndpoint().listMessages().setLimit(5).execute();
I would make sure you are using the same version of GCM APIs as you have JARs for. There have been quite a few revisions.
I am using the following code with gcm-server.jar, listed at 19718 bytes.
The code I successfully use to send GCM messages to a device is:
public void sendMessage() {
String notificationToken = mobileDevice.getPushNotificationCode();
String deviceType = mobileDevice.getDeviceType();
Sender sender = new Sender(BROWSER_API_KEY);
Message message = new Message.Builder().addData("message", "blah blah").build();
String device = "<the key for the device you are sending to goes here>";
try {
System.out.println("Sending message...");
Result result = sender.send(message, device, 5);
System.out.println("Done sending message");
if (result.getMessageId() != null) {
System.out.println("Got message ID: " + result.getMessageId());
System.out.println("Got error code name: " + result.getErrorCodeName());
System.out.println("result: " + result);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// Database has more than one record for this device.
// Replace all of this device's records with this new id
System.out.println("Got new canonical reg id: " + canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(com.google.android.gcm.server.Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister from database
System.out.println("Got error: " + error);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}