Android Broadcast not execute when clear from ram - android

Hi i created broadcast receiver which receive Battery level on Intent.ACTION_BATTERY_CHANGED event. It works good but when i remove this app from ram using swipe from holding home button then it doesnt receive event.
My code of Broadcast is
private BroadcastReceiver BatteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
Toast.makeText(BatteryIndicatorService.this,""+level, Toast.LENGTH_SHORT).show();
}
};

This can be done when your broadcast run in background for that you need to create service.In this service you have to define your Broadcast.
BatteryIndicatorService.java
public class BatteryIndicatorService extends Service {
private BroadcastReceiver BatteryReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
int level = intent.getIntExtra("level", 0);
Toast.makeText(BatteryIndicatorService.this,""+level, Toast.LENGTH_SHORT).show();
}
};
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
// Register Receiver.
registerReceiver(BatteryReceiver, new IntentFilter(
Intent.ACTION_BATTERY_CHANGED));
}
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
And Start it from MainActivity like
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start service in Background
startService(new Intent(this, BatteryIndicatorService.class));
}
Define Service in Manifest.xml in application tag
manifest.xml
<service
android:name="com.ittl.batteryindicator.BatteryIndicatorService"
android:enabled="true" >
</service>

Related

Montioring sensor values in Android to fire Notifications and then turning the sensor service off

I am trying to monitor the sensor values in Android through a service and if there is any change is the values of the sensor(Accelerometer)....it should fire a Notification and then the service should stop automatically...
But whats happening is that the service doesnot stop and it keeps firing notifications on every movement.
Can anyone suggest a better approach??
Sensor service
public class Sensored extends Service implements SensorEventListener {
SensorManager ssrmgr = null;
Sensor ssr = null;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
ssrmgr = (SensorManager) getSystemService(SENSOR_SERVICE);
ssr = ssrmgr.getDefaultSensor(Sensor.TYPE_SIGNIFICANT_MOTION);
ssrmgr.registerListener(this, ssr,SensorManager.SENSOR_DELAY_NORMAL);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float value = event.values[0];
if(value>0)
{
Intent i=new Intent();
i.setClass(this, NotifyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ssrmgr.unregisterListener(this);
stopSelf();
startActivity(i);
}
}
protected void onPause()
{
stopService(new Intent(getApplicationContext(), Sensored.class));
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
Notification class
public class NotifyActivity extends ActionBarActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Build notification
// Actions are just fake
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder noti = new NotificationCompat.Builder(this)
.setContentTitle("Inspire Me")
.setSmallIcon(R.drawable.ic_launcher)
.setSound(alarmSound);
noti.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// hide the notification after its selected
notificationManager.notify(001, noti.build());
}
}

Android service is not running in my application

My service class not running in background i have followed the sample tutorial, dont what is the issue and why its not running?
This is my Service class
public class Services extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.d("OnBind", "OnBind");
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Log.d("OnCreate", "OnCreate");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("OnStart", "OnStart");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
My Menifest
<service
android:name=".Services"
android:enabled="true" >
</service>
MyActivity to call the services
startService(new Intent(getApplicationContext(), Services.class));
Kindly look it out my coding and help me to run the app properly,
Thanks in Advance.
Check by providing the whole name of services class like com.example.Services rather than .Services in your manifest file.
For continiously running the service, do the following :
public class YourServiceName extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent i, int startId) {
this.test.run();
this.stopSelf();
}
public Runnable test= new Runnable() {
public void run() {
// Do something
}
};
}
The AlarmManager that starts it:
Intent testService = new Intent(this, YourServiceName .class);
PendingIntent pitestService = PendingIntent.getService(this, 0,testService,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pitestService);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, pitestService);
Hope this helps.

How start broadcast from prefrence to Activity

How send broadcast from prefrenceActivity to Activity.prefrenceActivity used for reset data of other activity.
In prefrenceActivity, there is a preference, when user click it a alert box open.If select yes then i want to start broadcast.
Code in Activity for receive broadcast
private BroadcastReceiver objResettedReceiver=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println(" broadCast receiver. . "+intent);
inc = 0;
initObjects();
}
};
register broadcast on Resume
IntentFilter localIntentFilter2 = new IntentFilter(SettingsActivity.broadcastAction);
this.registerReceiver(this.objResettedReceiver, localIntentFilter2);
unregiseter On pause & destroy Activity
protected void onPause() {
// TODO Auto-generated method stub
unregisterReceiver(objResettedReceiver);
super.onPause();
}
protected void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(objResettedReceiver);
super.onDestroy();
System.out.println("hi.. Activity Destroy.......");
}
Start broadcast
Intent intent = new Intent();
intent.setAction(broadcastAction);
sendBroadcast(intent);

How to auto Trigger Alarm Manager on its own instead of onClick

Below is my code which is working very fine. I am calling service after 10 seconds on click of button using Alarm Manager. I want to automate this process say every 10 minutes it should trigger on its own and call service irrespective of device in SCREEN_OFF or SCREEN_ON. Currently i also suspect call is from "Activity" due to which if I close the application it would not trigger.
/*MainActivity.java*/
package com.example.alarmservice;
public class MainActivity extends Activity implements OnClickListener{
final static private long ONE_SECOND = 1000;
final static private long TEN_SECONDS = ONE_SECOND * 10;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
findViewById(R.id.the_button).setOnClickListener(this);
}
private void setup() {
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
}
};
registerReceiver(br, new IntentFilter("com.example.alarmservice"));
//pi = PendingIntent.getBroadcast( this, 0, new Intent("com.authorwjf.wakeywakey"),0);
//am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
Intent intent = new Intent(MainActivity.this, ServiceClass.class);
pi = PendingIntent.getService(MainActivity.this, 0, intent, 0);
am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + TEN_SECONDS, pi);
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
}
Service Class
/*ServiceClass.java*/
package com.example.alarmservice;
public class ServiceClass extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d("Testing", "Service got created");
Toast.makeText(this, "ServiceClass.onCreate()", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "ServiceClass.onStart()", Toast.LENGTH_LONG).show();
Log.d("Testing", "Service got started");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}

Android bind service to own class

I guess I have more like a design issue than a "how to bind a service" issue. What I'm trying to do is to have a service running in a separate process that handles bluetooth communication. Further I have several tabs, within each another activity. The processing and UI events from each activity results in simple commands which have to be passed over bluetooth like "up", "down", "left" or "right". As the results in each tab activity are the same, I don't wnat to connect each with the service, and use the same message handler. So I created my own Handler object and a "connector" object. However I'm not sure how to connect this connector object with my service as it requries a context. Does it make sense to simply pass the application context to my connector object and bind it that way???
I'm open for any suggestions or hints
I'd suggest against using binding in this case. Actually, I'd suggest against binding in most use cases. Try to handle all communication between you Activities and the service running in another thread using intents only.
That means:
Send commands to the service from the activities by the .startActivity() method, passing the details of the actual command in the Intent's extras.
Receive events and result from the service in your activities by dynamically registered BroadcastReceivers. You register a listener in onResume() and unregister it in onPause() in you Activity. The service sends stuff only by broadcasting it (sendBroadcast()).
I prefer this architecture. It's loosely coupled and you can skip the annoying part where you're wondering if every one of your Activities unbinds correctly from you service when they're not using it. Also, you skip the pain of using IPC, which is a huge plus I think.
Here you are, my example .. will make you clear about that LOL
// My MyServiceInterface.aidl
package com.mad.exam;
interface MyServiceInterface{
int getNumber();
}
//MyService
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(this, "Service OnBind()", Toast.LENGTH_LONG).show();
return mBinder;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Destroyed ", Toast.LENGTH_SHORT).show();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "Service Started ", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
private final MyServiceInterface.Stub mBinder = new MyServiceInterface.Stub() {
public int getNumber() {
return new Random().nextInt(100);
}
};
}
//My Activity
public class ServiceDemo extends Activity implements OnClickListener {
MyServiceInterface mService;
ServiceConnection mConnection;
Button retreive;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.service);
retreive = (Button) findViewById(R.id.retreive);
retreive.setOnClickListener(this);
mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
mService = MyServiceInterface.Stub.asInterface(service);
try {
int i;
i = mService.getNumber();
Toast.makeText(ServiceDemo.this, "The service value is: " + String.valueOf(i),
Toast.LENGTH_SHORT).show();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("My Tag", "Clicked");
Button btn = (Button) v;
Intent callService = new Intent(this, MyService.class);
bindService(callService, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Intent callService = new Intent(this, MyService.class);
bindService(callService, mConnection, Context.BIND_AUTO_CREATE);
}
}

Categories

Resources