I want to display Battery level stats in my app. How can we obtain such information like Battery Power, Battery Voltage, etc.?
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale; /* This is your battery level */
}
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
or check out this guy (who wrote the code I posted): http://mihaifonoage.blogspot.com/2010/02/getting-battery-level-in-android-using.html
Is this of any help?
public class Main extends Activity {
private TextView contentTxt;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
contentTxt.setText(String.valueOf(level) + "%");
}
};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
contentTxt = (TextView) this.findViewById(R.id.monospaceTxt);
this.registerReceiver(this.mBatInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
}
Also, see this.
Related
Currentlly I am implementing pattern lock application and I want to set limit when user enter wrong pattern many time.Example,If user enter wrong pattern at that time set limit(3 or 4 time limit) and set delay 30 second and after 30 second give permission to enter pattern.
So,If anyone know how i can do this please give idea of that.
Here this my Reciever
public class LockScreenReceiver extends DeviceAdminReceiver {
Context context;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("Action...","..."+action);
//If the screen was just turned on or it just booted up, start your Lock Activity
if(action.equals(Intent.ACTION_SCREEN_OFF) || action.equals(Intent.ACTION_BOOT_COMPLETED))
{
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
#Override
public void onPasswordFailed(Context ctxt, Intent intent) {
DevicePolicyManager mgr = (DevicePolicyManager) ctxt.getSystemService(Context.DEVICE_POLICY_SERVICE);
int no = mgr.getCurrentFailedPasswordAttempts();
if (no >= 3) {
context.startActivity(new Intent(context,ChangeActivity.class));
}
}
}
Service
public class LockScreenService extends Service {
DeviceAdminReceiver receiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
// Register for Lockscreen event intents
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
receiver = new LockScreenReceiver();
registerReceiver(receiver, filter);
startForeground();
return START_STICKY;
}
// Run service in foreground so it is less likely to be killed by system
private void startForeground() {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(getResources().getString(R.string.app_name))
.setContentText("Running")
.setContentIntent(null)
.setOngoing(true)
.build();
startForeground(9999,notification);
}
#Override
#SuppressWarnings("deprecation")
public void onCreate() {
KeyguardManager.KeyguardLock key;
KeyguardManager km = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
//This is deprecated, but it is a simple way to disable the lockscreen in code
key = km.newKeyguardLock("IN");
key.disableKeyguard();
//Start listening for the Screen On, Screen Off, and Boot completed actions
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
//Set up a receiver to listen for the Intents in this Service
receiver = new LockScreenReceiver();
registerReceiver(receiver, filter);
super.onCreate();
}
#Override
public void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
}
Activity
public class MainActivity extends ActionBarActivity {
private Lock9View lock9View;
private static String MY_PREFS_NAME = "PatternLock";
private static String PATTERN_KEY;
SharedPreferences prefs;
Button btnChange;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(MainActivity.this, LockScreenService.class));
makeFullScreen();
setContentView(R.layout.activity_main);
btnChange = (Button)findViewById(R.id.btnChange);
btnChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(MainActivity.this,ChangeActivity.class);
startActivity(in);
}
});
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
lock9View = (Lock9View) findViewById(R.id.lock_9_view);
lock9View.setCallBack(new Lock9View.CallBack() {
#Override
public void onFinish(String password) {
PATTERN_KEY = prefs.getString("Pattern", "invalid");
if (PATTERN_KEY.equals("invalid")) {
Toast.makeText(MainActivity.this, "Options --> Create new Pattern", Toast.LENGTH_LONG).show();
} else {
if (password.equals(PATTERN_KEY)) {
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}else{
Context context = getApplicationContext();
// Create layout inflator object to inflate toast.xml file
LayoutInflater inflater = getLayoutInflater();
// Call toast.xml file for toast layout
View toastRoot = inflater.inflate(R.layout.layout_toast3, null);
Toast toast = new Toast(context);
// Set layout to toast
toast.setView(toastRoot);
toast.setGravity(Gravity.HORIZONTAL_GRAVITY_MASK | Gravity.BOTTOM,
0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
}
}
}
});
}
private void makeFullScreen() {
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if(Build.VERSION.SDK_INT < 19) { //View.SYSTEM_UI_FLAG_IMMERSIVE is only on API 19+
this.getWindow().getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
} else {
this.getWindow().getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE);
}
}
#Override
public void onBackPressed() {
return; //Do nothing!
}
public void unlockScreen(View view) {
//Instead of using finish(), this totally destroys the process
android.os.Process.killProcess(android.os.Process.myPid());
}
}
So,How i can achieve this...
Have a int field like failedCounter and increment it each time user inputs invalid patterns check if reached the limit then disable the input interface and have a handler to reset the value after the time delay.
int failedCount = 0;
final static int LIMIT = 5; //set your limit here
private void invalidPattern() {
if (++failedCount == LIMIT) {
//disable the input
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//reset the failed count
faildCount = 0;
//Enable the input interface here
}
}, 30000); // 30Sec delay
}
}
Use this two methods -
ScheduledThreadPoolExecutor c1;
private void IncorrectCallCounter() {
if (failedCounter>=0)
{
c1.shutdownNow();
LockScreenFor30Second();
}else
{
if (c1!=null)
c1.shutdownNow();
}
c1 = new ScheduledThreadPoolExecutor(1);
c1.schedule(new Runnable() {
#Override
public void run() {
failedCounter=0;
c1.shutdownNow();
}
}, 15, TimeUnit.SECONDS);
}
ScheduledThreadPoolExecutor c2;
private void LockScreenFor30Second() {
//Lock Screen Here
c2 = new ScheduledThreadPoolExecutor(1);
c2.schedule(new Runnable() {
#Override
public void run() {
//Unlock Screen Here
c2.shutdownNow();
}
}, 30, TimeUnit.SECONDS);
}
Declare failedCounter globally
private int failedCounter=0;
And call this method when you detect wrong pattern -
failedCounter=failedCounter+1;
IncorrectCallCounter();
If user enter wrong pattern 4 times in 15 seconds then this will call LockScreenFor30Second method. and inside LockScreenFor30Second add your code.
I am building app regarding battery indicator and i am using code from this post.
Getting battery status even when the application is closed
it is working fine when app is closed, but when an app is active or on foreground it did not work or did not send any broadcast.
This is main activity from i start service
public class Main extends Activity {
private MyService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (service == null) {
Intent i = new Intent(this, MyService.class);
startService(i);
}
finish();
}
}
Following is the service code.
public class MyService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand");
// do not receive all available system information (it is a filter!)
final IntentFilter battChangeFilter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
// register our receiver
this.registerReceiver(this.batteryChangeReceiver, battChangeFilter);
return super.onStartCommand(intent, flags, startId);
}
private final BroadcastReceiver batteryChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
checkBatteryLevel(intent);
}
};
private void checkBatteryLevel(Intent batteryChangeIntent) {
// some calculations
final int currLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_LEVEL, -1);
final int maxLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_SCALE, -1);
final int percentage = (int) Math.round((currLevel * 100.0) / maxLevel);
if(percentage==100)
{
Intent intent = new Intent(getBaseContext(), Last.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);
}
// do not forget to unregister
unregisterReceiver(batteryChangeReceiver);
} }
And when following activity start i did not receive any broadcast.
public class Last extends Activity {
Button btnCancel;
Uri notification;
Ringtone r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last);
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
btnCancel = (Button) findViewById(R.id.stopsound);
btnCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
r.stop();
}
});
} }
As I understood,
when you start application in first time, you see nothing, just service is started and a broadcast receiver is registered. When battery level will be changed, the method checkBatteryLevel() is calling and the broadcast receiver will be unregistered. As result you have never received a new changing of battery level.
I am trying to monitor the current battery status using a Service. I wrote some code and I can show the battery level using the log once but I want to monitor the battery level according to a timer every 5 seconds.
public class ServiceStatusUpdate extends Service {
GPSTracker gps;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
while (true) {
new Handler().postDelayed(new Runnable() {
public void run() {
batteryLevel();
Log.e("Status changed", "Status changed");
}
}, 5000);
return START_STICKY;
}
}
private void batteryLevel() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
Log.e("Batarry status iss", level + "mm");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
return;
}
}
MainActivity.java:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, ServiceStatusUpdate.class));
}
}
manifest.xml source:
<receiver
android:name=".OnBootReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".ServiceStatusUpdate"
android:enabled="true" />
OnBootReceiver:
public class OnBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
//int batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
Intent serviceLauncher = new Intent(context, ServiceStatusUpdate.class);
context.startService(serviceLauncher);
}
}
}
I am also trying to send an HTTP request every /xxx times. The HTTP request will include some text, the battery status, and latitude and longitude.
I know how to send the request with parameters, but my service is working only once.
You are unregistering the batteryLevelReceiver after the first time it receives a broadcast. Remove this line from onReceive to continue to receive broadcasts:
context.unregisterReceiver(this);
Also, you probably only want to register and unregister your broadcast receiver once when the server is created/destroyed so you should register in onCreate and unregister in onDestroy.
Here is some code that should be very close to what you want. Note that all of this will run on the UI thread currently.
public class ServiceStatusUpdate extends Service {
private static final int CHECK_BATTERY_INTERVAL = 5000;
private GPSTracker gps;
private double batteryLevel;
private Handler handler;
private BroadcastReceiver batInfoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent batteryIntent) {
int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
if (rawlevel >= 0 && scale > 0) {
batteryLevel = (rawlevel * 100.0) / scale;
}
Log.e("Battery status is", batteryLevel + "mm");
}
};
private Runnable checkBatteryStatusRunnable = new Runnable() {
#Override
public void run() {
//DO WHATEVER YOU WANT WITH LATEST BATTERY LEVEL STORED IN batteryLevel HERE...
// schedule next battery check
handler.postDelayed(checkBatteryStatusRunnable, CHECK_BATTERY_INTERVAL);
Log.e("Battery status is", batteryLevel + "mm cached");
}
};
#Override
public void onCreate() {
handler = new Handler();
handler.postDelayed(checkBatteryStatusRunnable, CHECK_BATTERY_INTERVAL);
registerReceiver(batInfoReceiver,
new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
#Override
public void onDestroy() {
unregisterReceiver(batInfoReceiver);
handler.removeCallbacks(checkBatteryStatusRunnable);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
}
Hello every one I am developing an app in which I am getting battery level and displaying it in a textview. Now I want to increase this level 1% after each 5 sec and want to show this increment.
I have tried following code but i can't get my output
java code
public class ChargingActivity extends Activity {
TextView textBatteryLevel = null;
int level;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context ctxt, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
// add your stuff here
level++;
}
}
, 5000);
textBatteryLevel.setText(String.valueOf(level) + "%");
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chargingactivity);
textBatteryLevel = (TextView) findViewById(R.id.btrylevel);
this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
But Level of Battery is not increasing after each 5 sec. What I am doing wrong?
I'd suggest using the postDelayed(...) method of the View class and also don't use an actual BroadcastReceiver.
For example, Intent.ACTION_BATTERY_CHANGED is a STICKY broadcast and as such doesn't need a BroadcastReceiver to handle it. Instead if we pass null as the first parameter to the registerReceiver(...) method, no receiver is actually registered but the return from that call is the Intent from the sticky broadcast. Example...
Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
The next step is to setup the 5 second update for the TextView. The Android View class has a postDelayed(...) method which accepts a Runnable parameter as well as a delay in milliseconds. Example...
textBatteryLevel.postDelayed(levelChecker, 5000);
The postDelayed(...) method of View is a one-shot (non-repeating) 'post' so make sure it is reset within the run() method of the Runnable each time it is called.
I haven't tested the following code but I think it should work. Bear in mind however, there's no guarantee that the level of battery charge will change within any 5 second period. It probably takes about 1 minute per 1% to charge my tablet and similar on my phone so I certainly wouldn't expect to see an update to the TextView every 5 seconds.
public class ChargingActivity extends Activity {
TextView textBatteryLevel = null;
int level;
LevelChecker levelChecker = new LevelChecker();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chargingactivity);
textBatteryLevel = (TextView) findViewById(R.id.btrylevel);
// Get the current battery level
Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
// Set the starting level
textBatteryLevel.setText(String.valueOf(level) + "%");
}
#Override
protected void onResume() {
super.onResume();
textBatteryLevel.postDelayed(levelChecker, 5000);
}
#Override
protected void onPause() {
textBatteryLevel.removeCallbacks(levelChecker);
}
private class LevelChecker extends Runnable {
#Override
public void run() {
Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int currentLevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
if (currentLevel != level) {
level = currentLevel;
textBatteryLevel.setText(String.valueOf(level) + "%");
}
textBatteryLevel.postDelayed(levelChecker, 5000);
}
}
}
Move text changing code inside TimerTask.
Timer timer = new Timer();
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context ctxt, Intent intent) {
level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
timer.schedule(new TimerTask() {
public void run() {
level++;
textBatteryLevel.setText(String.valueOf(level) + "%");
}
}
, 5000);
}
};
I want do develop an Android App, which calculates the battery app
So here's my idea how to do that: When the user starts the app, the app gets the battery level of the phone (For example: 80%). And after 1h the app gets the battery status again (Then it is for example: 76%). The calculation: in 1h the battery loses 4%, that means the battery will last about 20h (80/4)
I know, how to get the battery status, etc..
My question: How can I set the countdown for 1h in the background? There shouldn't be any textView where the countdown is displayed. The coundown needs to run in the background. How can I do that?
I googled and found this, but this isn't working: (I put these method in onCreate()
CountDownTimer countDownTimer = new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
IntentFilter intFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
}
};
}
#Override
public void onFinish() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
Toast toast = Toast.makeText(context, "Battery: " + level/4, Toast.LENGTH_LONG); // this is just, to check, if the countDown is still running
toast.show();
}
};
}
};
You need register once your broadcast receiver.
//in Oncreate
...
IntentFilter intFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
BatteryReceiver batteryReceiver = new BatteryReceiver();
registerReceiver(batteryReceiver , intFilter);
...
public class BatteryReceiver extends BroadcastReceiver {
int startlevel = 0;
long lastUpdateTime = 0;
boolean isStartCheck = false;
#Override
public void onReceive(Context context, Intent intent) {
if(!isStartCheck){
startlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
lastUpdateTime = System.currentTimeMillis();
isStartCheck = true;
} else {
if((System.currentTimeMillis() - lastUpdateTime)/1000 > 3600) {
// 1h was going. do your work.
reset();
}
}
}
public void reset() {
lastUpdateTime = System.currentTimeMillis();
isStartCheck = false;
startLevel = 0;
}
}