Android App Is Causing Battery Drain - android

I have two issues with this, my very first android app. The first is that I noticed after I installed the app the battery started draining about twice as fast as before. I read an article on this that stated sometimes programmers make an error which causes this. This being my first app, the probability is pretty high that this is the case.
The second issue is that I can save my variables when the app is turned off, but when the phone is turned off the data is lost.
As for the code, it's mostly bits and pieces from stuff I've found online and tried to incorporate. It's a simple calculator with three variables. Ideally, I'd like to store b and c, but allow the user to overwrite them. Variable a will change with each use, so no need to store that.
Here's my Main:
package com.kwagz.calc;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
String g, e;
String b; //changed(sorry)
String c; //changed
SharedPreferences sh_Pref;
Editor toEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadSavedPreferences();
}
public void calculateClickHandler(View view) {
if (view.getId() == R.id.button1) {
EditText a = (EditText)findViewById(R.id.a);
EditText b = (EditText)findViewById(R.id.b);
EditText c = (EditText)findViewById(R.id.c);
TextView output = (TextView)findViewById(R.id.textView9);
double gp = Double.parseDouble(a.getText().toString());
int ab = Integer.parseInt(b.getText().toString());
int ac = Integer.parseInt(c.getText().toString());
double t = ((gp / ab) * ac);
output.setText(String.format("%.2f", t));
}
}
public void sharedPreferences() {
SharedPreferences saved_values =//there's no linebreak here in my code
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor=saved_values.edit();
editor.putString("b", b);
editor.putString("c", c);
editor.commit();
}
private void loadSavedPreferences() {
SharedPreferences saved_values =//there's no linebreak here in my code
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
b = saved_values.getString("b", g);
}
}

From reading what you said, the only logical explanation forming in my head is: You are starting background service from your App, while background service is running it makes app run all the time which explains why variables are stored until phone is turned off (when background service gets killed).

Okay, let's take your questions one at a time. The battery problem could be a number of things, without knowing more details about your program I couldn't possibly diagnose it completely. Android does have some good power saving tips. The key item is to minimize the use of connectivity devices to no more than is required. The two biggest culprits are GPS and Internet connections. If your app isn't running, then the only way it could be running the batteries is if there's threads in the background, or maybe something like an AlarmService.
You are using SharedPreferences correctly, the value should be saved, but I think you should but the saving code in onSaveInstanceState(). If you do that, it should work fine.
EDIT
Upon closer inspection, you're fundementally saving the wrong thing. You should save the value of the EditText, not the EditText itself. In fact, I'd simply remove all references to String a,b,c, move the EditText definitions to the top to replace them, and do something like this:
editor.putString("b", b.getText().toString());
b.setText(saved_values.getString("b", g));

I've conducted several tests in an effort to recreate the issue, with no success. I'm still working on the sharedPreferences thing, but the battery drain (I suspect) was caused by another app which just happened to coincide with the installation of mine.
As I mentioned in my note to arleitiss, my Y!Mail was showing the highest amount of battery drain. A day or two after posting the note my account started acting up and then became "inactive". Once I reset it, the app no longer appears on the Battery list.
Thanks for all the input!

Related

SystemClock() is not public in 'android.os.SystemClock'

I'm trying to code the game loop for an android game, however, i've come across this error when trying to access the current time (you know, for FPS management etc)
"SystemClock() is not public in 'android.os.SystemClock'. Cannot be accessed from outside package"
My code:
import android.os.SystemClock;
//...
SystemClock clock = new SystemClock();
Can you help me please? ^_^
SystemClock exposes static methods. So you should access them like this:
SystemClock.sleep(1000);
boolean b = SystemClock.setCurrentTimeMillis(1000)
long l = SystemClock.currentThreadTimeMillis();

How do I activate NFC without a readable/writable device nearby?

For an engineering project I need to basically trick my phone to come out of NFC searching mode and into a mode where the phone is continuously putting out energy. Obviously I have activated NFC in the settings, but the only way I can trick it into leaving the searching mode and have it put out energy continuously is if I leave it on top of a blank tag.
I was thinking of implementing this NFC beam function: public boolean invokeBeam (Activity activity) and implanting it into the BeamLargeFiles sample code provided in Android studio, posted below.
I'm new to app development (though I have a fair bit of coding experience) so I'm just not sure if it's feasible, or if I'm looking in the right places. Any thoughts, ideas and help is appreciated!
package com.example.android.beamlargefiles;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.widget.TextView;
import android.view.Menu;
import com.example.android.common.activities.SampleActivityBase;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogFragment;
import com.example.android.common.logger.LogWrapper;
import com.example.android.common.logger.MessageOnlyLogFilter;
/**
* A simple launcher activity containing a summary sample description
* and a few action bar buttons.
*/
public class MainActivity extends SampleActivityBase {
public static final String TAG = "MainActivity";
public static final String FRAGTAG = "BeamLargeFilesFragment";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView sampleOutput = (TextView) findViewById(R.id.sample_output);
sampleOutput.setText(Html.fromHtml(getString(R.string.intro_message)));
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
BeamLargeFilesFragment fragment = new BeamLargeFilesFragment();
transaction.add(fragment, FRAGTAG);
transaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/** Create a chain of targets that will receive log data */
#Override
public void initializeLogging() {
// Wraps Android's native log framework.
LogWrapper logWrapper = new LogWrapper();
// Using Log, front-end to the logging chain, emulates android.util.log method signatures.
Log.setLogNode(logWrapper);
// Filter strips out everything except the message text.
MessageOnlyLogFilter msgFilter = new MessageOnlyLogFilter();
logWrapper.setNext(msgFilter);
// On screen logging via a fragment with a TextView.
LogFragment logFragment = (LogFragment) getSupportFragmentManager()
.findFragmentById(R.id.log_fragment);
msgFilter.setNext(logFragment.getLogView());
logFragment.getLogView().setTextAppearance(this, R.style.Log);
logFragment.getLogView().setBackgroundColor(Color.WHITE);
Log.i(TAG, "Ready");
}
}
From the beamlargedata sample code provided by android studio
When no suitable NFC device is in range the NFC controller will constantly search all technologies for a tag or peer-to-peer device. It does this by sending out short bursts separated by no field activity (to save power).
If you have a newer device it is also very likely that the NFC Controller will only generate a very weak RF field to save power. This field is not strong enough to power a NFC tag but is strong enough for the chip to detect if there is something resonating at 13.56Mhz.
With standard Android you cannot change this behaviour. There is no programatical way in the API to enable the mode you're looking for.
However, if you can stretch your requirements a bit you can likely get something close to what you want.
Option 1:
Enable the Reader-Mode. Call enableReaderMode using the EXTRA_READER_PRESENCE_CHECK_DELAY extra. Set this to the a very high value.
Now, if a tag enters the RF field the NFC controller won't check for presence that often anymore. You can activate your RF field by touching a tag, then removing it.
The RF field will be stable until the presence check delay expires.
Option 2:
If rooting the device is an option, you can hack yourself into the low level NFC stack. Each NFC controller that I've worked with so far has one or more test modes for antenna calibration. Just outputting an RF field is one of the very common test modes.
Reading the source-code of the nfc-stack will likely show you how to enable such a mode. That takes some digging in the source-code and is not for the faint heart, but it is doable.

AS3 - Loading Image Coordinates from URL

I am developing an Android App in Air for Android using Flash Pro CC & I am tired of pushing updates all the time to change a spawn location for an image that needs to move every few days to a specific location. I won't know the location until just minutes before the update needs to be pushed & it would be much faster to simply have the app load the spawn coordinates for the image upon launch from my website in a .txt file. I would need something where I just type the X and Y coordinates in a file & then the information is loaded and AS3 spawns the image at those coordinates. If no coordinates are available in the text file (as 5 days of the week there won't be), I need a different image to be displayed wherever I place it. I will probably just have a separate frame for that though.
Any help is greatly appreciated & I'd prefer it if the image can be used in a motion tween but if not then I will work something out.
NOTE: I am new to AS3 coding but I have Flash itself figured out for animating with the timeline.
Have a look at URLRequest and URLLoader for retrieving the data. For spawning the image at a specific location, consider just moving it instead; Any object on stage is a DisplayObject, and DisplayObjects have properties x and y. For swapping out the images, look at DisplayObjectContainer, specifically the functions DisplayObjectContainer.addChild(child:DisplayObject) and DisplayObjectContainer.removeChild(child:DisplayObject). I have provided links to the documentation for each of the relevant functions.
If the update is on a daily basis, have a look at the Date class too - that will allow you to find out what date it is and whether you need to make an url request to load the textfile to display the image.
If you have any specific questions regarding the use of these classes, I think it's best if you make a new question with a link back to this one for context. You're good with English, not so good with AS3 (as you say), so I could explain the relevant bits where needed, but it would be a long and complex story if I were to explain this entire functionality in one go. ... I think you'll find that these class names will make googling easier too.
I expect that you'll have to use an URLLoader with an URLRequest to load the textfile, then depending on the results, display the image by adding it to stage via addChild if it's not there yet, and then setting its x and y values. You'll have to use the Date class to check whether you need to make a new request every time the user starts the application or does some specific action.
I have the finished code here. loadURL is the Document Class loaded by Flash. Everything works great!
package {
// IMPORTS EVENTS USED
import flash.display.MovieClip;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.UncaughtErrorEvent;
import flash.events.ErrorEvent;
import flash.events.Event;
// DECLARES VARIABLES
public class loadURL extends MovieClip {
public var Xurl:String = "URL GOES HERE";
public var Yurl:String = "URL GOES HERE";
public var URLloaderX:URLLoader = new URLLoader();
public var URLloaderY:URLLoader = new URLLoader();
public var marker:Marker = new Marker();
public var gone:Gone = new Gone();
public var connectionerr:ConnectionErr = new ConnectionErr();
// CODE EXECUTED UPON LAUNCH
public function loadURL() {
// constructor code
trace("Loaded");
URLloaderX.addEventListener(Event.COMPLETE, completeHandlerX);
URLloaderX.load(new URLRequest(Xurl));
URLloaderY.addEventListener(Event.COMPLETE, completeHandlerY);
URLloaderY.load(new URLRequest(Yurl));
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);
}
function completeHandlerX(event:Event):void
{
if(URLloaderX.data == null||URLloaderX.data==(""))
{addChild(gone)}
else{addChild(marker);marker.x = (URLloaderX.data)}
}
function completeHandlerY(event:Event):void
{
if(URLloaderY.data == null||URLloaderY.data==("")){}
marker.y = (URLloaderY.data)
}
private function onUncaughtError(e:UncaughtErrorEvent):void //Checks for no internet connection
{
e.preventDefault(); //leave this
// RESULT OF NO INTERNET HERE
addChild(connectionerr);
}
}
}

How to capture MMI code result?

Is it possible to capture MMI result in Android?
I need to do things like put on hold, merge calls, etc. and as the only telephony events in android are NEW_OUTGOING_CALL, RINGING, OFFHOOK and IDLE, I need to get the result when i dial any MMI code like Held Code.
Is it possible?
The best solution for me would be to find some way to discover when an outgoing call gets actually connected. Maybe has somebody find any workaround for that?
I made some progress in that question reading system logs (LogCat) and searching for determinate strings, but it seems that logs differs between models and SO versions so this is not a consistent aproach.
Thanks for your help!
Maybe you can get it using RIL(Radio Interface Layer)
try something like:
1) adb device shell
2) logcat -b radio
// Navigate to the page that you have dial *#06# in dialpad then execute jar below to get the IMEI result
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import android.util.Log;
public class SIM_Info_Reader_png extends UiAutomatorTestCase{
public void getPromptedIMEI() throws UiObjectNotFoundException {
UiObject list = new UiObject(new UiSelector().resourceId("android:id/text1"));
int i = 0;
System.out.println("IMEI=" + list.getText());
}
}

Android App crashes in emulator - logs blank

I am completely new to android, and pretty much a Java newb.
I have a simple app that I am building to get the hang of android's development environment - and things like click events, etc..
The app loads, and I am able to change the text in a textfield using a button handler. However, when I import the location class, and try to do a simple GPS call, the application crashes.
The problem is, everything looks good in Eclipse (error console) - and I'm not seeing any exceptions in the android emulator (DevTools). I have the logcat window open, but I haven't done anything in eclipse/code to send logcat anything (do I need to?)
Can anyone see something wrong with this? Is there a better way to troubleshoot?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import android.location.*;
public class locationDisplay extends Activity {
private EditText text;
private Location GPSLocation;
double dblLat;
double dblong;
String strLat;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // bind the layout to the activity
text = (EditText) findViewById(R.id.EditText01);
text.setText("No button pressed");
}
// Handler for each button -- Button01 is when it crashes
public void myClickHandler(View view) {
switch (view.getId()) {
case R.id.Button01:
dblLat = GPSLocation.getLatitude();
strLat = Double.toString(dblLat);
text.setText(strLat);
break;
case R.id.Button02:
text.setText("Button 2 was clicked");
break;
case R.id.Button03:
text.setText("Button 3 was clicked");
break;
}
}
You shouldn't need to write anything to get the default messages in LogCat; uncaught exception reports should appear automatically when your program crashes. However, sometimes LogCat and your emulator get disconnected from each other and the messages simply all disappear. Simply close Eclipse and the emulator, restart them both, and the messages should reappear. An easy way to tell whether the link has been re-established is during the boot-up of the emulator. Just as the flashing "ANDROID" text in the fancy font disappears bringing you to the lockscreen, you should see about a hundred lines of text flash by on LogCat. If that doesn't happen, then LogCat isn't getting its messages.
The way to display debugging messages in Android is to use the Log.d("some name for your log statements so you can filter the LogCat messages", "The actual debug statement here");. You'll often find people using things like a static final String LOG_TAG in their application so that they can make sure their logs always have the same tag, and hence, the filter never misses a message.
As for your actual code here, Rpond is right, you never initialised your GPSLocation object.
You GPSLocation object is null. You need to access the LocationService to get a current location. And with the emulator you will need to manually send locations.
Location Services
Sometimes LogCat 'forgets' you have a device/emulator connected and running. It seems like this happens after you have a device and an emulator online at the same time and then you disconnect one of them. If you are getting nothing from LogCat, go to Window>Show View>Other>Devices and then click the device that you want to log.

Categories

Resources