TrafficStats class provides total data since boot can I directly access internet data usage from android
e.g Call history can be directly fetched from call log.
So is it possible to get internet data from internet data usage.
And how to get internet data usage on the basic of application ?
so for I know we cannot directly get internet data usage from android as we fetch call history record form call log we can get data form TrafficStats class which is since boot
To get internet data on application basic here is the simple code using packageManager to get package name of the corresponding app and using ApplicationInfo we can find the detail of the application information
final PackageManager pm = context.getPackageManager();
// get a list of installed apps.
List<ApplicationInfo> packages = pm.getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
// get the UID for the selected app
UID = packageInfo.uid;
String package_name = packageInfo.packageName;
Log.d("mypackagename",package_name+"");
ApplicationInfo app = null;
try {
app = pm.getApplicationInfo(package_name, 0);
} catch (PackageManager.NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String name = (String) pm.getApplicationLabel(app);
Drawable icon = pm.getApplicationIcon(app);
// internet usage for particular app(sent and received)
double received = (double) TrafficStats.getUidRxBytes(UID)
/ (1024 * 1024);
double send = (double) TrafficStats.getUidTxBytes(UID)
/ (1024 * 1024);
double totalab = received + send;}
Related
I've got a dental camera and iam try to get windows to press space when the camera button is pressed
I have the OEM software and driver installed, it works perfect, gets the feed and makes a snapshot when camera button is pressed. I need to use another software for the feed and the snapshot, the software gets the feed but doesn't react to camera button, it only reacts to space key press(part of the oem driver), so my way of solving this was getting the device by product id and listening the button press event and remapping it space press.
I am pretty much stuck at this point.
How can I listen on events coming from the device I've got?
public static Device findDCam(){
// Create the libusb context
Context context = new Context();
// Initialize the libusb context
int result = LibUsb.init(context);
if (result < 0)
{
throw new LibUsbException("Unable to initialize libusb", result);
}
// Read the USB device list
DeviceList list = new DeviceList();
result = LibUsb.getDeviceList(context, list);
if (result < 0)
{
throw new LibUsbException("Unable to get device list", result);
}
try
{
// Iterate over all devices and list them
for (Device device: list)
{
DeviceDescriptor descriptor = new DeviceDescriptor();
result = LibUsb.getDeviceDescriptor(device, descriptor);
if (result < 0)
{
throw new LibUsbException(
"Unable to read device descriptor", result);
}
if(descriptor.idProduct()== -3810){
System.out.println("D cam found");
return device;
}
}
}
finally
{
// Ensure the allocated device list is freed
LibUsb.freeDeviceList(list, true);
}
// Deinitialize the libusb context
LibUsb.exit(context);
return null;
}
I've also thought that maybe it's impossible using usb4java since as far as i understood, if i want to listen on the usb port i need to take control from the driver and then its pointless.
Maybe iam going all wrong and i should use the driver instead?
Or maybe there is an app that can read button presses from a specific device and remap it?
If the camera has a standard driver, this should work through this video capture SDK. To quick test it, run the demo executable included in the package, select the camera in the list, check the "webcam snapshot button" checkbox and start the camera. Then press the camera button to test the snapshot.
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'm writing a program for importing contacts from an ERP system to Outlook. Different emails will receive different lists of contacts from ERP. The idea here is, in each email I have a public contact folder that can be accessed by a technical user. The technical user can write contacts into this folder. Here is the code for searching the folder:
protected FolderId findFolderId(String folderDisplayName, String userEmail) throws Exception {
Mailbox userMailbox = new Mailbox(userEmail);
FolderId contactRootFolder = new FolderId(WellKnownFolderName.Root, userMailbox);
FolderId result = null;
FolderView view = new FolderView(Integer.MAX_VALUE);
view.setPropertySet(new PropertySet(BasePropertySet.IdOnly, FolderSchema.DisplayName));
view.setTraversal(FolderTraversal.Deep);
FindFoldersResults findFolderResults = this.service.findFolders(contactRootFolder, view);
//find specific folder
for (Folder f : findFolderResults) {
if (folderDisplayName.equals(f.getDisplayName())) {
result = f.getId();
}
}
return result;
}
The service object is created as follows:
this.service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials(userName, passWord);
this.service.setCredentials(credentials);
try {
this.service.setUrl(new URI(URL));
} catch (URISyntaxException e) {
LOGGER.error(e);
}
Where URL is the end point for the Exchange server (for Office 365 it is https://outlook.office365.com/EWS/Exchange.asmx).
The code works with Office 2010, I get the Id from that folder, connect to it and save the contacts. After the migration to Office 365, we can't find the public folder. It can just find a folder with the name "PeoplePublicData". (I don't even know that folder exists.)
Throttling in Office365 means your code will only return the first 1000 folder in the Mailbox so if what your looking for isn't within that result set that would be one reason. I would suggest you get rid of
FolderView view = new FolderView(Integer.MAX_VALUE);
and change it to
FolderView view = new FolderView(1000);
and then page the results https://msdn.microsoft.com/en-us/library/office/dn592093(v=exchg.150).aspx which will allow you to get all the Folder in a Mailbox. Also unless you are looking for something in the Non_IPM_Subtree of the Mailbox start the search with MsgFolderRoot eg
FolderId contactRootFolder = new FolderId(WellKnownFolderName.MsgFolderRoot, userMailbox);
That will reduce the number of folders returned.
Also why don't you use a SearchFilter to search for the folder you are after eg https://msdn.microsoft.com/en-us/library/office/dd633627(v=exchg.80).aspx this would eliminate the need to page the results,
I implemented GCM for push notifications like stated in the Android Guide (https://developer.android.com/google/gcm/client.html) in one of my apps. The app and notifications are working fine on Kitkat and Lollipop.
But lastly I became some mails from users that upgraded their phones from to Lollipop. With that the notifications will not be displayed anymore. Only solution so far is to remove the app and reinstall it from the appstore.
Did someone face a similar problem and if so, did you find a solution to fix it?
This is a GCM ID issue. Try using Thread.sleep and retry for a number of times, till the GCM ID is recieved.
int noOfAttemptsAllowed = 5; // Number of Retries allowed
int noOfAttempts = 0; // Number of tries done
bool stopFetching = false; // Flag to denote if it has to be retried or not
String regId = "";
while (!stopFetching)
{
noOfAttempts ++;
GCMRegistrar.register(getApplicationContext(), "XXXX_SOME_KEY_XXXX");
try
{
// Leave some time here for the register to be
// registered before going to the next line
Thread.sleep(2000); // Set this timing based on trial.
} catch (InterruptedException e) {
e.printStackTrace();
}
try
{
// Get the registration ID
regId = GCMRegistrar.getRegistrationId(LoginActivity.this);
} catch (Exception e) {}
if (!regId.isEmpty() || noOfAttempts > noOfAttemptsAllowed)
{
// If registration ID obtained or No Of tries exceeded, stop fetching
stopFetching = true;
}
if (!regId.isEmpty())
{
// If registration ID Obtained, save to shared preferences
saveRegIDToSharedPreferences();
}
}
The Thread.sleep and noOfAttemptsAllowed can be played around with based on your design and other parameters. We had a sleep time of 7000 so that probability of getting registered at first attempt is higher. However, if it fails, the next attempt would consume another 7000ms. This might cause users to think your app is slow. So, play around intelligently with those two values.
Whats the better solution to sync images according with path:
Database - Web Service - Mobile Application
In my database, I have a blob field as images. So, I need the to transfer images for web service and mobile application.
I found the solution (attempt) but large images always return out of memory. Solution below:
In my web service, I use the json API to store the blob images to integrate. See, I create image as base64 thats no problem for small images but large images (2000 items), triggers out of memory. So, my code below:
public void getImages(String date) throws Exception {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
if (date != null) {
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASS);
Statement s = connection.createStatement();
ResultSet r = s.executeQuery("select * from images");
while (r.next()) {
JSONObject o = new JSONObject();
byte[] imageBytes = r.getBytes("image");
String imageBase64 = DatatypeConverter.printBase64Binary(imageBytes);
o.put("image", imageBase64);
jsonArray.put(o);
}
jsonObject.put("images", jsonArray);
} catch (SQLException e) {
System.out.println(e);
}
}
}
In my mobile application, read the json and decode base64 to each image after show image. So, I dont need to store the images in mobile disk or web service disk.
The mobile application will to work offline. Any idea to solve my problem?
Don't encode your images directly into JSON. Rather return a server URL that separately serves up the image.
Tip of #Alan Krueger. It's better solution, encode images in json is bad idea.