How to know when the services has ended - android

I want know when the service has ended, so I use BroadcastReceiver.
My service name is CheckNuevosAvisosIntentServices and I launch it in main.java (onCreate method) as:
Intent msgIntent = new Intent(Main.this, CheckNuevosAvisosIntentService.class);
msgIntent.putExtra("iteraciones", 1);
startService(msgIntent);
My manifest inside application tag.
<!-- Services -->
<service android:name="com.kirolm.instalacionesdep.services.CheckNuevosAvisosIntentService" />
In another fragment (HomeFragment) I use isMyServiceRunning method and BroadcastReceiver class:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (CheckNuevosAvisosIntentService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
My Broadcast code is this:
public class ProgressReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {
Log.e("Testing", "The service is running...");
}
else if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
Log.e("Testing", "The service has been ended");
}
}
}
and in creathe method (HomeFragment) I implements this:
if(!isMyServiceRunning()){
Log.e("Testing", "HomeFragment: The service is running");
}else{
Log.e("Testing", "HomeFragment: The servie stop");
}
CheckNuevosAvisosIntentServicescode:
public class CheckNuevosAvisosIntentService extends IntentService{
public static final String ACTION_PROGRESO = "com.kirolm.instalacionesdep.services.action.PROGRESO";
public static final String ACTION_FIN = "com.kirolm.instalacionesdep.services.action.FIN";
public CheckNuevosAvisosIntentService() {
super("CheckNuevosAvisosIntentService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
int iter = intent.getIntExtra("iteraciones", 0);
for(int i=1; i<=iter; i++) {
Intent bcIntent = new Intent();
bcIntent.setAction(ACTION_PROGRESO);
bcIntent.putExtra("progreso", i*10);
sendBroadcast(bcIntent);
}
buscaNuevasNoticasRss();
Intent bcIntent = new Intent();
bcIntent.setAction(ACTION_FIN);
sendBroadcast(bcIntent);
}
private void buscaNuevasNoticasRss() {
// TODO Auto-generated method stub
//This method checks. When this method finish I want finish my services.
}
}
When buscaNuevasNoticiasRssfinish, I want finish my services.
I receive when the service is running but I don't receive when the service stop.
Edited: HomeFragment (onCreat method)
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ProgressReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("Testing", "HomeFragment. BoradcastReceiver. Dentro de onReceive");
if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service is running...");
}
else if(intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service has been ended");
}
}
};
}

Override the onDestroy() method of your IntentService and send a broadcast to your receiver saying the service is destryed.
public class CheckNuevosAvisosIntentService extends IntentService{
//Your code
.......
.......
#Override
public void onDestroy() {
super.onDestroy();
sendBroadcast(new Intent(CheckNuevosAvisosIntentService.ACTION_FIN));
}
}
And create a BroadcastReceiver as an inner class of HomeFragment.
private class HomeFramgnet extends Fragment {
private ProgressReceiver progressReceiver;
Override
public void onCreate(Bundle savedInstanceState) {
progressReceiver = new ProgressReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(CheckNuevosAvisosIntentService.ACTION_PROGRESO);
intentFilter.addAction(CheckNuevosAvisosIntentService.ACTION_FIN);
registerReceiver(progressReceiver, intentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(progressReceiver);;
}
class ProgressReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("Testing", "HomeFragment. BoradcastReceiver. Dentro de onReceive");
if (intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service is running...");
} else if (intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
Log.e("Testing", "HomeFragment. BoradcastReceiver. The service has been ended");
}
}
}
}

Related

Unable to receive Broadcast

I am sending a Broadcast from my Service and trying to receive in my Activity but I don't see it receiving. Can someone suggest if I am doing something wrong. I am seeing onResume getting called but don't see flag
Log.d("InchooTutorial", msg_for_me);
getting logged.
Service Code :
Intent sendableIntent = new Intent("SOTGSAMReceiver");
sendableIntent.putExtra("kicked", prefs.getSurveySubmittedStatus(context));
LocalBroadcastManager.getInstance(AcrService.this).sendBroadcast(sendableIntent;
Activity Code :
// Get Broadcast
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.d("InchooTutorial", "Inside onResume");
IntentFilter intentFilter = new IntentFilter("SOTGSAMReceiver");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// extract our message from intent
String msg_for_me = intent.getStringExtra("kicked");
// log our message value
Log.d("InchooTutorial", msg_for_me);
}
};
// registering our receiver
this.registerReceiver(mReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// unregister our receiver
this.unregisterReceiver(this.mReceiver);
}
If you are using LocalBroadcastManager to send broadcast you need to register with it.
Write for register:
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, intentFilter);
And for unregister:
LocalBroadcastManager.getInstance(this).unregisterReceiver(this.mReceiver);
public class BroadcastService extends Service {
private final static String TAG = "BroadcastService";
public static final String COUNTDOWN_BR = "com.sixmod.com.sixmod.MyReceiver";
Intent bi = new Intent(COUNTDOWN_BR);
Intent ci = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(180000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#Override
public void onFinish() {
ci.putExtra("countdownFinish", 1);
sendBroadcast(ci);
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
#Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
In Activity
private BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent); // or whatever method used to update your GUI fields
}
};
#Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(br, new IntentFilter(BroadcastService.COUNTDOWN_BR));
Log.e("Receiver Registered", "Registered broacast receiver");
}
#Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(br);
Log.e("Unregistered", "Unregistered broacast receiver");
}
#Override
public void onStop() {
try {
getActivity().unregisterReceiver(br);
} catch (Exception e) {
// Receiver was probably already stopped in onPause()
}
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void updateGUI(Intent intent) {
if (intent.getExtras() != null) {// here you fetch the data

How to get broadcast for screen lock in android

How to get trigger that screen is locked or on in android??
i tried using SCREEN_OFF & SCREEN_ON action in broadcast receiver but it's not working.
public void onReceive(Context context, Intent intent) {
Log.d("XYZ", "Screen ON/OFF");
Toast.makeText(context, "screen",10000).show();
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
.......
}
}
in activity i have registered broadcast like-
screen is object of my broadcast receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mContext.registerReceiver(screen, filter);
Call the UpdateService.class within your MainActivity.class .
startService(new Intent(MainActivity.this, UpdateService.class));
UpdateService.class
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
public static int countOn = 0;
public static int countOff = 0;
#Override
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
Log.i("UpdateService", "Started");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_ANSWER);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
Log.i("onDestroy Reciever", "Called");
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.i("screenON", "Called");
Log.i("viaService", "CountOn =" + countOn);
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
Log.i("viaService", "CountOff =" + countOff);
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Receiver class
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
// Log.i("via Receiver","Normal ScreenOFF" );
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
} else if(intent.getAction().equals(Intent.ACTION_ANSWER)) {
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
Hey try using dynamic calling of broadcast,I tried this it will surly work...
public class MainActivity extends Activity {
//Create broadcast object
BroadcastReceiver mybroadcast = new BroadcastReceiver() {
//When Event is published, onReceive method is called
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.i("[BroadcastReceiver]", "MyReceiver");
if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.i("[BroadcastReceiver]", "Screen ON");
}
else if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.i("[BroadcastReceiver]", "Screen OFF");
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(mybroadcast, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
}

Creating my own action for BroadcastReceiver

I have an method like this:
public static boolean checkConnection(){
if(getConnection()!=null){
return true;
}else
return false;
}
I trying to listen to the result of this method throughout my application. Till my application is alive. Only inside my application
How should I create my own action so that in BroadcastReceiver I can listen to this method and show an dialog when it returns false and hide the dialog automatically when it start returning true?
How and what will be the best approach to do this?
public class BroadCastActivity extends Activity implements OnClickListener{
ConnectionReceverLocal mReceverLocal;
Button mSwithcOn,mSwitchOff;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_broad_cast);
/*Intent intent = new Intent();
intent.setAction("com.broadcast.myconnectionbroadcast");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);*/
mReceverLocal = new ConnectionReceverLocal();
mSwitchOff = (Button)findViewById(R.id.switchoff);
mSwithcOn = (Button)findViewById(R.id.switchon);
mSwitchOff.setOnClickListener(this);
mSwithcOn.setOnClickListener(this);
}
private void sendMessage() {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.d("Connection result Checking Asynctasks", ""+ConnectionProvider.checkConnection());
return ConnectionProvider.checkConnection();
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
Intent intent = new Intent("com.broadcast.myconnectionbroadcast");
// Add data
intent.putExtra("message", result);
LocalBroadcastManager.getInstance(BroadCastActivity.this).sendBroadcast(intent);
}
}.execute();
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceverLocal);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mReceverLocal,
new IntentFilter("com.alignminds.broadcast.myconnectionbroadcast"));
sendMessage();
}
public class ConnectionReceverLocal extends BroadcastReceiver {
public ConnectionReceverLocal() {
}
#Override
public void onReceive(Context context, Intent intent) {
AlertDialog.Builder mDBuilder = new AlertDialog.Builder(BroadCastActivity.this);
Boolean intentAction = intent.getBooleanExtra("message", false);
if(intentAction==false)
{
Log.d("Connection is false in broadcast recever", "Connection is false");
if(mDBuilder!=null)
{
mDBuilder.setMessage("No Network");
mDBuilder.create().show();
}
}else {
Log.d("Connection is true in broadcast recever", "Connection is true");
if(mDBuilder!=null)
{
mDBuilder.setMessage("Network Ok");
mDBuilder.create().show();
}
}
}
}
#Override
public void onClick(View v) {
if(v==mSwithcOn)
{
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
if(v==mSwitchOff)
{
WifiManager wifiManager = (WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
}
}
}
Send a broadcast with whatever action you want like this
Intent intent = new Intent();
intent.setAction("my_fancy_action");
intent.putExtra(EVENT_MESSAGE, message);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Subclass BroadcastReceiver class to listen for broadcasts
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
// Do something
}
Register your receiver to listen to the broadcast
IntentFilter filter = new IntentFilter();
filter.addAction("my_fancy_action");
LocalBroadcastManager.getInstance(context).registerReceiver(myReceiver, filter);

Android wait for WiFi scan to finish

i'm trying to wait for the wifi scan to finish in the broadcast receiver!.
I have 1 Activty (ChooseActivity extends Activity) and 1 class (Scan).
In my Activity i call Scan class to scan wifi and return boolean (true) when finish, here is the code.
My purpose is to separate the scan of my activity because i call scan class in several places.
public class ChooseActivity extends Activity implements OnClickListener{
private int idMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose);
idMap = this.getIntent().getExtras().getInt("ID_MAP");
((Button)this.findViewById(R.id.scan_button)).setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.scan_button:
Scan scan = new Scan();
Toast.makeText(getApplicationContext(), " "+scan.scanHotspots(idMap), Toast.LENGTH_SHORT).show();
break;
}
}
}
And here is my Scan class
public boolean scanHotspots(int idMap){
wifiManager = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
wifiManager.startScan();
receiver = new Receiver();
IntentFilter intentFilter = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
context.registerReceiver(receiver, intentFilter);
//HERE I WANT STOP EXECUTION TO WAIT test VAIRABLE CHANGE STATUS
return test;
}
public class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
{
test=true;
}
}
}
}
Thank you in advance.

android Activity and a service with sms contentobserver

My app requirements
The application will have an activity and a service.
The service has a sms contentobserver.
After application installation the Service should run all the time irrespective of
application active or not
The registration and unregistration of contentobserver inside the service should
be controlled from the activity.
On uninstallation of the application the service should be destroyed.
I tried some code. In oncreate of the service i have done resgitartion of content observer
and ondestroy i unregistered it. I have used start and stop service from the activity.
But even after stop service the onchange method of the content observer is still getting called.
please let me know some sample code and the manifest definition of this service.
public class MyActivity extends ListActivity implements OnInitListener {
#Override
protected void onDestroy() {
super.onDestroy(); // let it be here as per the android TTS samples
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent sintent = new Intent(MyActivity.this,MyService.class);
MyActivity.this.startService(sintent);
}
private boolean SSMyservice() {
// TODO Auto-generated method stub
//stop service
Intent sintent = new Intent(MyActivity.this,MyService.class);
MyActivity.this.stopService(sintent);
//do some work
//start service again
MyActivity.this.startService(sintent); //start service again
return true;
} //importdata
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.TTSread:
return true;
case R.id.SSS:
SSMyservice();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Log.v(TAG,"option menu created");
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.layout.omenu, menu);
return true;
}
}
------------end MyActivity---------------------
----------------------------------
public class MyService extends Service {
protected SmsObserver smsSentObserver=null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
registersmsevent();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
return Service.START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregistersmsevent();
}
public void registersmsevent() {
// TODO Auto-generated method stub
if(smsSentObserver == null)
{
final Uri SMS_STATUS_URI = Uri.parse("content://sms");
smsSentObserver = new SmsObserver(new Handler());
MyService.this.getContentResolver().registerContentObserver(SMS_STATUS_URI, true, smsSentObserver);
}
}
public void unregistersmsevent() {
if(smsSentObserver != null)
{
MyService.this.getContentResolver().unregisterContentObserver(smsSentObserver);
smsSentObserver = null;
}
}
public class SmsObserver extends ContentObserver {
Handler handler;
public SmsObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
this.handler = handler;
}
#Override
public boolean deliverSelfNotifications() {
return true;
}
#Override
public void onChange(boolean selfChange) {
//my code........
super.onChange(selfChange);
}
}//End of class SmsObserver
}//end of service
I could fix the issue. This was a timing issue. Stopping service takes sometime.

Categories

Resources