Update battery level through service class as background process - android

Hello friends I'm developing an Battery android application. which show battery level(%) on Status bar after closing application. I start an service class that run as background process and put some code.
Notificationservice.java
public void onCreate(){
super.onCreate();
IntentFilter filter= new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus= getApplicationContext().registerReceiver(null, filter);
int status= batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
batteryLevel= String.valueOf(status);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//make the toast message
Toast.makeText(this, "Service Started"+batteryLevel+"%", Toast.LENGTH_LONG).show();
//show the notification on status bar
NotificationManager nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent2= new Intent(this, MainActivity.class);
PendingIntent pendingIntent= PendingIntent.getActivity(getApplicationContext(), 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mbuilder= new
NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Battery Level: "+batteryLevel+"%")
.setContentText("Battery Level: "+batteryLevel+"%")
.setContentIntent(pendingIntent);
nm.notify(notificationID, mbuilder.build());
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(getApplicationContext(), "service Destroy", Toast.LENGTH_SHORT).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
In MainActivity.java
rotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1= (Button) findViewById(R.id.button1);
b2= (Button) findViewById(R.id.button2);
tv= (TextView) findViewById(R.id.textView1);
createListener();
}
private void createListener() {
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Notificationservice.class));
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Notificationservice.class));
}
});
}
When I press run application run properly but when I press start Service button battery level shows on status bar but it doesn't change/update it remains same. friends please help, what should I do....???

you need to start the service or notification from broadcast receiver..just register a broadcast to get battery level..and from onreceive() method of receiver..call notification or start a service..

Related

unable to stop service using AlarmManger in android

public class myserveclass extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
.
public class MainActivity extends ActionBarActivity {
CheckinternetConnection internet;
TextView textview;
int tempint = 100;
private static final long REPEAT_TIME = 1000 * 5;
private PendingIntent pendingIntent;
Button button1;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textview);
internet = new CheckinternetConnection();
schedueService();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(internet, filter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(internet);
}
class CheckinternetConnection extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Utils.isNetworkAvailable(MainActivity.this)) {
textview.setVisibility(View.GONE);
startService(new Intent(getBaseContext(), myserveclass.class));
} else {
textview.setVisibility(View.VISIBLE);
textview.setText("It Seems Internet Connection is off");
stopService(new Intent(getBaseContext(), myserveclass.class));
}
}
}
public void schedueService() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(MainActivity.this, myserveclass.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0,
intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
1000 * 10, pintent);
}
}
this is my code for start service and stop service am able to start service when app is connected with internet and stop when internet is off but after 10 second again service becomes start please check my issue where am doing wrong i have used alarm manger please check please suggest me where am doing wrong .
You need to CANCEL the alarm to stop the service
Intent intent = new Intent(MainActivity.this, myserveclass.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0,
intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pintent);
Hope it helps ツ

Android Service again created after stopped once

i have created a simple service just periodically Toasting. But when service is stopped once it creates again by own and again continuously starting.
Following is my MainActivity code.
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(this, TestService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int i;
i=15;
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
i* 1000, pintent);
Button startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(getBaseContext(), TestService.class));
}
});
Button stopBtn = (Button) findViewById(R.id.stopBtn);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(new Intent(getBaseContext(), TestService.class));
}
});
}
Following is my service class
Testservice
public class TestService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Created", 1).show();
Log.i("TestService", "SERVICE START");
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Destroy", 1).show();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
return super.onStartCommand(intent, flags, startId);
}
}
That's all my code when button clicked to stop service it once stopped but again created but it's own
what's I am doing wrong??
Thanks in advance..
Try to use START_STICKY :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
If its still not working, try returning START_REDELIVER_INTENT instead of START_STICKY.
Check this link for more information :
START_STICKY and START_NOT_STICKY
Try
MainActivity.this
instead of getBaseContext()
I have fixed my problem as My AlarmManager was periodically sending intent request to my service so I stopped service and also stopped my AlarmManger by alarm.cancel(pintent);
Thanks to all of you..

Continue service when app is killed

I have an activity with two buttons (ON and OFF): when I click the ON button a service starts. When I click the OFF botton the service stops. Now, my service does not have problems apart from when I kill the app from "Recent Apps" because in this circumstance the service restarts. I don't want that it restarts but I want that it continues working. The service is a START_STICKY.
This is my "service" code:
#Override
public void onCreate() {
// TODO Auto-generated method stub
myServiceReceiver = new MyServiceReceiver();
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
}
public class LocalBinder extends Binder {
SensorService getService() {
return SensorService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (!running){
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MY_ACTION_FROMACTIVITY);
registerReceiver(myServiceReceiver, intentFilter);
running = true;
sensorManager=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), SensorManager.SENSOR_DELAY_NORMAL);
}
//return super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onDestroy() {
Log.v(TAG,"destroy");
// TODO Auto-generated method stub
sensorManager.unregisterListener(this);
mNM.cancel(NOTIFICATION);
this.unregisterReceiver(myServiceReceiver);
super.onDestroy();
}
private void showNotification() {
CharSequence text = getText(R.string.activity);
Notification notification = new Notification(R.drawable.lifestyle, text, System.currentTimeMillis());
SharedPreferences flagNot = getSharedPreferences("flagNotification", 0);
final SharedPreferences.Editor editor = flagNot.edit();
editor.putBoolean("flagNotification",true);
editor.commit();
Intent notificationIntent = new Intent(this, ActivityTab.class);
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.app_name),text, contentIntent);
notification.flags |= Notification.FLAG_NO_CLEAR;
// Send the notification.
mNM.notify(NOTIFICATION, notification);
}
public void onAccuracyChanged(Sensor sensor,int accuracy){
}
public void onSensorChanged(SensorEvent event){
......
}
public class MyServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
int hostCmd = arg1.getIntExtra(CMD, 0);
if(hostCmd == CMD_STOP){
running = false;
stopSelf();
}
}
}
}
Can you help me,please?
Many thanks.
Implement startForeground in your service and send it a persistent notification.
private void startForeground() {
int ID = 1234;
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(getBaseContext());
builder.setContentIntent(pendIntent);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setTicker("CUSTOM MESSAGE");
builder.setWhen(System.currentTimeMillis());
builder.setAutoCancel(false);
builder.setContentTitle("Test Service");
builder.setContentText("CUSTOM MESSAGE");
Notification notification = builder.build();
startForeground(ID, notification);
}

How to cancel an alarm in service from an activity?

I have a brodcastReciver , an activity and a service , in the activity i send an intent to service to set an alarm , and alarm is sending broadcast to brodcastReciver to show toast.
but i cant cancel alarm from activiy. here is my code :
public class MainActivity extends Activity {
Button start, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
start();
}
});
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stop();
}
});
}
void stop() {
Intent i = new Intent(this, Reci.class);
i.putExtra("c", "cancel");
startService(i);
Toast.makeText(this, "stop clicked!", Toast.LENGTH_SHORT).show();
}
void start() {
Intent i = new Intent(this, Serv.class);
i.putExtra("d", "do");
startService(i);
Toast.makeText(this, "start clicked!", Toast.LENGTH_SHORT).show();
}
}
service :
public class Serv 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) {
if (intent.getStringExtra("d").equalsIgnoreCase("do")) {
Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, Reci.class)
.setAction("ir.test.code.Reci.noti");
PendingIntent pi = PendingIntent.getBroadcast(this, 1234, i, 0);
G.AM.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 5000, 5000, pi);
} else if (intent.getStringExtra("c").equalsIgnoreCase("cancel")) {
Toast.makeText(this, "onCancel", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, Reci.class)
.setAction("ir.test.code.Reci.noti");
PendingIntent pi = PendingIntent.getBroadcast(this, 1234, i, 0);
G.AM.cancel(pi);
}
return super.onStartCommand(intent, flags, startId);
}
}
broadcastReciver
public class Reci extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("ir.test.code.Reci.noti")) {
Toast.makeText(context, "ir.test.code.Reci.noti",
Toast.LENGTH_SHORT).show();
}
}
}
and Application class :
public class G extends Application{
public static AlarmManager AM;
#Override
public void onCreate() {
super.onCreate();
AM = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
}
what should i do?
you are not starting service because of diffent class name you provided ...change void stop() method
Intent i = new Intent(this, Reci.class);
to
Intent i = new Intent(this, Serv.class);
in stop() method of mainactivity

Service not being killed via PendingIntent

I have a service that posts a notification, and what I am trying to do is kill that service when the notification is clicked. Here is my code:
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
super.onCreate();
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification n = new Notification(R.drawable.ic_launcher,
getResources().getString(R.string.notify_body),
System.currentTimeMillis());
n.setLatestEventInfo(getApplicationContext(),
getResources().getString(R.string.notify_title), getResources()
.getString(R.string.notify_body), PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(
this, StopSelf.class), Intent.FLAG_ACTIVITY_NEW_TASK));
n.defaults = Notification.DEFAULT_ALL;
nm.notify(ID, n);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
nm.cancel(ID);
}
public class StopSelf extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
stopService(new Intent(this, myService.class));
this.finish();
}
}
When I click the notification the statusbar is dismissed, but the notification is still there. Why isn't StopSelf killing the service and calling onDestroy?

Categories

Resources