[DEV]Any one heard about BatteryStatusImpl class from private api - Java for Android App Development

Any android gurus out there who have used this class previously ???
I instantiate the class using the following code:
Code:
IBatteryStats mIStats = IBatteryStats.Stub.asInterface(
ServiceManager.getService("batteryinfo"));
byte[] data = null;
try {
data = mIStats.getStatistics();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Parcel parcel = Parcel.obtain();
parcel.unmarshall(data, 0, data.length);
parcel.setDataPosition(0);
BatteryStatsImpl mStats = BatteryStatsImpl.CREATOR.createFromParcel(parcel);
but BatteryStatsusImpl writesin the log:
File corrupt: battery history buffer too large (a big num)
and nothing happens the app just stops responding
and no Battery Data Available is displayed
through the debugger i got to know that the batteryinfo service returned data but still no result
I use the restricted apis as is in the AP14 android git without any modification
what do I do? please help i need to get per app battery usage.

Related

Application Request for Weight Watchers Points Calculator

Can someone make a .cab or an .exe program to calculate Weight Watchers points? I found this article on the internet where it looks like someone as already done it but they did not post it. Here is the article
http://geekswithblogs.net/cdahlinge...-mobile-meets-weight-watchers--mvp-style.aspx
Craig Dahlinger
<< Presenting at Richdmond code camp 2008.2 | Home | mshtml – the ongoing adventure >> windows mobile meets weight watchers : MVP style Ok, so I know it has been a long time since a post, but it has been really busy with work and family. I have been busy coding and learning lots of new stuff. I work with a great bunch of developers and my current team lead is a great mentor.
Well for the new year the wife and I decided to get back into shape. I started hitting the gym and so did she but she is also doing weight watchers with a friend. One of the things they do is they have to calculate points on a daily basis. These points are comprised of calories, fat and fiber. There is a formula for these three which in turn results in the number of points a particular item is. A few months ago I convinced the wife to get a windows mobile device (woo hoo!) and she is a good power user. So one night she asks me, “Is there a way I can just enter in the calories, fat and fiber on my phone and it tell me how many points something is?”. I did some searching and there are numerous online versions of the calculator but no native ones for windows mobile. I found the formula here, and started to get to work.
I wanted to approach this application using the MVP design pattern. I know it may be overkill for this simple of an application but I thought it would be good practice.
I started with the interface for the data model, in this case it would be the main caloric properties of food.
namespace WWPC.Common.Interfaces{ public interface IFoodModel { int Fiber { get; set; } int Calories { get; set; } float Fat { get; set; } int Points { get; set; } int CalculatePoints(); }}I then wrote up the interface for the view for the model.
namespace WWPC.Common.Interfaces{ public interface IFoodCalcView { int Calories { get; } int Fiber { get; } float Fat { get; } int Points { set; } event EventHandler DataChanged; }}Next, came the interface for the presenter.
public interface IFoodCalcPresenter { void OnCalculatePoints(); }
Ok, now that I got my main interfaces in place, time to code up the implementation. I started with the model first since this was the class that would provide the implementation for calculating the caloric points. Using the formula mentioned above, the CalculatePoints() method came out like so:
public int CalculatePoints(){ var calories = Convert.ToDecimal(Calories); var cal = calories / 50; var totalFat = Convert.ToDecimal(Fat); var fat = totalFat / 12; var fiber = Convert.ToDecimal(Fiber); return Points = Convert.ToInt32(Math.Round(cal + fat - (fiber/5), 0)); } With the model complete, I then moved to the presenter. The presenter would be responsible for binding the model to the view responding to the data changes in the view and rebinding those changes to the model. I made the presenter with an overloaded constructor to take a view and a model. The presenter then binds to the data changed event on the view which enables the presenter to update the model from the view. The OnCalculatePoints() method will update the view with the points value after using the model for calculation.
namespace WWPC.Common{ public class FoodPresenter : IFoodCalcPresenter { private readonly IFoodCalcView _View; private readonly IFoodModel _Model; public FoodPresenter(IFoodCalcView view, IFoodModel model) { _View = view; _View.DataChanged += new EventHandler(_View_DataChanged); _Model = model; } void _View_DataChanged(object sender, EventArgs e) { SetModelFromView(); } private void SetModelFromView() { _Model.Calories = _View.Calories; _Model.Fat = _View.Fat; _Model.Fiber = _View.Fiber; } #region IFoodCalcPresenter Members public void OnCalculatePoints() { _View.Points = _Model.CalculatePoints(); } #endregion }}
With the presenter done it was time to implement the view. I wanted a simple mobile form where you can enter in data quickly and then calculate the results. I initially tried using a label to display the result, but did not like it. I then tried a mobile gauge control, but that took up too much space on the small screen. Finally I decided to use the notification class for windows mobile. I did not use the managed wrapper version, I used the the version created by Christopher Fairbairn, found here. This version has an awesome implementation which exposes many features of the notification class. I wanted to give the user the ability to dismiss the notification when they were done reading the results. Also using the notification class the UI was able show the needed text boxes for entry and the SIP panel along with the results without needing to scroll the screen. Here is a screen shot of the main form.
Now with the controls in place on the form, I can implement the view. The form creates a new presenter and passed into it a new model during construction. When the calculate menu option is clicked the main form raises the data changed event then calls the OnCalculateMethod on the presenter. When the presenter binds the model to the view, during the set of the points value, the notification is shown to the user via the ShowNotification method.
namespace WWPC.Calc{ public partial class WWPCalculator : Form, IFoodCalcView { private readonly FoodPresenter _Presenter; private NotificationWithSoftKeys _Notification; public WWPCalculator() { InitializeComponent(); _Presenter = new FoodPresenter(this,new FoodModel()); } public int Calories { get { return (string.IsNullOrEmpty(txtCalories.Text)) ? 0 : Int32.Parse(txtCalories.Text); } } public int Fiber { get { return (cmbFiber.Text == "4 or more") ? 4 : (string.IsNullOrEmpty(cmbFiber.Text)) ? 0 :Int32.Parse(cmbFiber.Text); } } public float Fat { get { return (string.IsNullOrEmpty(txtFat.Text)) ? 0 : float.Parse(txtFat.Text); } } public int Points { set { ShowPointsNotification(value); } } public event EventHandler DataChanged; private void mnuExit_Click(object sender, EventArgs e) { this.Close(); } private void mnuCalculate_Click(object sender, EventArgs e) { if (DataChanged != null) this.DataChanged(sender, e); _Presenter.OnCalculatePoints(); } private void mnuClear_Click(object sender, EventArgs e) { txtCalories.Text = string.Empty; txtFat.Text = string.Empty; cmbFiber.Text = "0"; } private void ShowPointsNotification(int points) { _Notification = new NotificationWithSoftKeys { Text = String.Format("Total Points:{0}", points), Caption = "Weight Watchers Point Calculator", RightSoftKey = new NotificationSoftKey(SoftKeyType.Dismiss, "Dismiss"), }; _Notification.RightSoftKeyClick+=new EventHandler(_Notification_RightSoftKeyClick); _Notification.Visible = true; } void _Notification_RightSoftKeyClick(object sender, EventArgs e) { if (_Notification == null) return; _Notification.Visible = false; _Notification = null; } }}
Now, when it is all put together, it looks like so.
Below is a link to the source code. The project was done using Visual Studio 2008 against the windows mobile 5 sdk. It will also work against windows mobile 6 sdk, I just chose version 5 since that is the common sdk. Thanks for reading!!

[Q] Android permissions inside the framework

Hi,
I added a system service into the framework (hence running in the system_process). Via Binder.getCallingUid() I can determine the calling process/app. So far so good.
But if my service tries to use other system services (e.g. the LocationManager) a SecurityException is thrown because LocationManager thinks it is called by the original app that called my service.
From what I understood, system services have all permissions by default, so this should not be the case, should it?
From programming4.us/Mobile/1304.aspx:
Binder services are free to make other binder calls, but these calls always occur with the service’s own identity (UID and PID) and not the identity of the caller.
Click to expand...
Click to collapse
Here some code to illustrate the problem:
Code:
public class MyService implements IInterface {
public IBinder asBinder() {
return mBinder;
}
private final IMyService.Stub mBinder = new IMyService.Stub() {
public Bundle doSomething() {
int uid = Binder.getCallingUid(); // uid of the calling app
int myUid = Process.myUid(); // my uid == 1000
...
try {
ILocationManager lm = ILocationManager.Stub.asInterface(ServiceManager.getService("location"));
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
} catch (Exception e) {
SecurityException is thrown. Requires ACCESS_FINE_LOCATION
}
}
};
}
Thanks in advance for any help or comments!
Just in case anyone faces the same problem:
Calling Binder.clearCallingIdentity() solves the problem.

[Q] In-App-Billing

Hello,
i've some issues to implement the in-app-billing system; here'S the code:
Code:
case R.id.item2:
new Thread(new Runnable() {
public void run() {
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("developersupported");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
try {
Bundle skuDetails = mService.getSkuDetails(3,
getPackageName(), "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList
= skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
//if (sku.equals("sup")) mPremiumUpgradePrice = price;
}
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
try {
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
"developersupported", "inapp", "payed");
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(pendingIntent.getIntentSender(),
1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
Integer.valueOf(0));
} catch (SendIntentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The code is from the documentaion "Implementing In-app Billing (IAB Version 3)".
the app conmects to google but the after loaing, theres this error like "your product wasnt found".
If the code correct? i set up an item in the developer console with the name "developersupported".
If you wanna try, the app is called "Clapperboard" in the Play Store
Thanks in advance!
ueen
Sometimes it takes a while for Google's servers to understand that you actually launched a new IAP item. What you can do is:-
1)Sign and export your apk and then upload it as draft . Using the same apk test it locally.
2)Also I recommend using the updated Billing v3 API. The previous v3 had some bugs and it hence has been fixed.
3)Wait and watch. You'll find the item in some hours....
I've had this experience with this.
Pls Give a thanks if this post helped you!
Sent from my Nexus 4 using XDA Premium 4 mobile app
boggartfly said:
Sometimes it takes a while for Google's servers to understand that you actually launched a new IAP item. What you can do is:-
1)Sign and export your apk and then upload it as draft . Using the same apk test it locally.
2)Also I recommend using the updated Billing v3 API. The previous v3 had some bugs and it hence has been fixed.
3)Wait and watch. You'll find the item in some hours....
I've had this experience with this.
Pls Give a thanks if this post helped you!
Sent from my Nexus 4 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
Well i waited over 12h and it still doesnt work.
whats that with the updated v3? I cant post links but if xou go to the devloper android page heres the path /google/play/billing/billing_integrate.html theres the code from.
Is the code correct?
I published the non app with the nonfunctionable in-app-billing and i really like to fix this fast! Please help!
ueen said:
Hello,
i've some issues to implement the in-app-billing system; here'S the code:
Code:
case R.id.item2:
new Thread(new Runnable() {
public void run() {
ArrayList<String> skuList = new ArrayList<String> ();
skuList.add("developersupported");
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
try {
Bundle skuDetails = mService.getSkuDetails(3,
getPackageName(), "inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList
= skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
//if (sku.equals("sup")) mPremiumUpgradePrice = price;
}
}
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
try {
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(),
"developersupported", "inapp", "payed");
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(pendingIntent.getIntentSender(),
1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0),
Integer.valueOf(0));
} catch (SendIntentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The code is from the documentaion "Implementing In-app Billing (IAB Version 3)".
the app conmects to google but the after loaing, theres this error like "your product wasnt found".
If the code correct? i set up an item in the developer console with the name "developersupported".
If you wanna try, the app is called "Clapperboard" in the Play Store
Thanks in advance!
ueen
Click to expand...
Click to collapse
Use the samples available for In app billing . What you can do is extract code which is suitable and port it to where you want. Also copy relevant class files. Please also give credit to the original developer who wrote the code as it is kanging someone else's code..
That's the easiest way to get up and running. Don't worry about anything else buddy. Keep coding.
ok i solved the issue by de installing the debug vrsion and installing the appstore version of my app.
thanks for your support.
btw: i used the samples from the google android documentation.
Sometimes it takes a while for Google's servers to understand that you actually launched a new IAP item. What you can do is:-
1)Sign and export your apk and then upload it as draft . Using the same apk test it locally.
2)Also I recommend using the updated Billing v3 API. The previous v3 had some bugs and it hence has been fixed.
3)Wait and watch. You'll find the item in some hours....
I've had this experience with this.
Pls Give a thanks if this post helped you! 
Sent from my Nexus 4 using XDA Premium 4 mobile app
Click to expand...
Click to collapse
I told you. See point number 1.
Also do read the other documentation if necessary.
Please give a thanks if you think this post helped you!
Sent from my Nexus 4 using XDA Premium 4 Mobile App .

Getting ANR in concurrent DB access

I have used content provider in my project and override the applyBatch() for writting data into the database :
@override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final Context context = getContext();
final SQLiteDatabase db = getDatabase(context);
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
If there is any writing operation to the database, applyBatch() method get called and in same time if I will make query from database(using CursorLoader), or call apply batch from different activity ANR comes and the following exception will also comes :
W/SQLiteConnectionPool(18025): The connection pool for database '+data+data+com.abc.xyz+databases+XYZ' has been unable to grant a connection to thread 8073 (pool-17-thread-3) with flags 0x2 for 64.105 seconds.
W/SQLiteConnectionPool(18025): Connections: 0 active, 1 idle, 0 available.
The above issue will not come if I remove the methode db.beginTrasaction() and db.endTrasaction() from applyBatch(). But in that case reading/writing time becomes large. I have used methods db.beginTrasaction() and db.endTrasaction() which reduces database access time to ten times.
Is there any approach, so that SQLite DataBse response quickly and there is no ANR ?

[Q] Overlay an image prior to taking screenshot

Hello everyone,
I'm new to java-android programming and have what is probably a very basic question.
I purchased some source code to reskin and whoever wrote the code was either sloppy or very talented because it's difficult for me to follow with my limited training.
I've managed to get through most of what I wanted to do but this part is throwing me off.
I have a button that captures the current screen view and brings up an intent share popup window allowing the user to select whatever program they have for sharing the screenshot.
That works fine, however the app has a banner add at the bottom of the screen that I would like to overlay with another image when the user presses the share button. Then after the screenshot is saved I want the overlayed image to disappear and they can continue on.
// Here is a code snip-it of what I have that works for capturing and sharing:
case R.id.ShareButton:
// Capture the screenshot:
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, getString(R.string.myImage)+".png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage( getContentResolver(), b,
"Screen", "screen");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Share the screenshot:
Intent share = new Intent(Intent.ACTION_SEND);
// If you want to share a png image only, you can do:
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
// Make sure you put example png image named myImage.png in your
// directory
String imagePath = Environment.getExternalStorageDirectory()
+ "/myImage.png";
File imageFileToShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Post your WINNINGS!"));
break;

Categories

Resources