Unable to receive Broadcast - android

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

Related

Android get information from service

I made an service that triggers every 10 sec. How to connect service to activity when it triggers. Example i refresh my local DB, when appears an update Activity send an Toast.
AlarmService.class
#SuppressLint("SimpleDateFormat")
public class AlarmService extends Service {
Handler mHandler;
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
}
public void f() {
Toast t = Toast.makeText(this, "Service is still running",
Toast.LENGTH_SHORT);
t.show();
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
Toast t = Toast.makeText(this, "Service started", Toast.LENGTH_SHORT);
t.show();
// TODO Auto-generated method stub
super.onStart(intent, startId);
mHandler = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
f();
mHandler.postDelayed(this,10000);
}
};
mHandler.postDelayed(r, 10000);
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent = new Intent(this,AlarmService.class);
startService(serviceIntent);
}
}
Use broadcast receiver like this
public static class MyExtBroadcastReceiver extends BroadcastReceiver {
public MyExtBroadcastReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
//Call your activity here
}
Make a method for setting the alarm
public void setAlarm(){
f(); // call your method f() here
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
Intent alarmintent1 = new Intent(this, MyExtBroadcastReceiver.class);
PendingIntent sender1=PendingIntent.getBroadcast(this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
try {
am.cancel(sender1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ex....."+e);
}
Calendar cal=Calendar.getInstance();
cal.add(Calendar.Seconds,10);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*10*60, sender1);
Call this method from OnCreate()
#Override
public void onCreate() {
setAlarm();
}
}
You can use LocalBroadcastManager, Messenger, ResultReceiver to send data from service to Activity.
Here is an example that uses ResultReceiver to send updated data from Service to Activity.

How to call another activity after destroy() of service is called

In this code I have created a service.After 3 seconds i want to destory this service and want to call another activity in destroy method.but this doesnt seem to work.
public class TimerService extends Service
{
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent,int flags,int startId)
{
new CountDownTimer(3000, 1000)
{
public void onTick(long millisUntilFinished)
{
}
public void onFinish()
{
stopSelf();
}
}.start();
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy()
{
super.onDestroy();
Intent i = new Intent(this,Dummy.class);
i.putExtra("SessionTimedOut","Expire");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(i);
}
}
Activity which calls My Service
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this,TimerService.class);
startService(i);
}
}
Try to insert the code to the finish method:
#Override
public int onStartCommand(Intent intent,int flags,int startId)
{
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(this,Dummy.class);
i.putExtra("SessionTimedOut","Expire");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
stopSelf();
}
}, 3000);
return super.onStartCommand(intent,flags,startId);
}

how to turn off android service or turn off Reciever?

How can I turn off Service in Android? OR How can I unregiser or turn off Reciever?
public void onDestroy() doesn't work
This is my Service
public class LockScreenService extends Service{
BroadcastReceiver mReceiver;
public static volatile boolean isMustBeLocked;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
KeyguardManager.KeyguardLock k1;
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
if(isMustBeLocked) {
KeyguardManager km = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
k1 = km.newKeyguardLock("IN");
k1.disableKeyguard();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new LockScreenReceiver();
registerReceiver(mReceiver, filter);
super.onCreate();
}
else{
Log.e("LockScreenService","TEST");
}
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
/*#Override
public void onPause(){
}*/
public void destroy(){
if(mReceiver!=null) {
unregisterReceiver(mReceiver);
Log.e("","TEST destroy3");
}
Log.e("","TEST destroy2");
}
#Override
public void onDestroy() {
if(mReceiver!=null) {
unregisterReceiver(mReceiver);
Log.e("","TEST destroy");
}Log.e("","TEST destroying");
super.onDestroy();
}
}
To turn off the service:
Intent intent = new Intent(this, Service.class)
stopService(intent);
To unregister Receiver be sure to first :
unregisterReceiver(mybroadcast);
Service- you call stopService. Inside the service you can call stopSelf. Receivers you call unregisterReceiver (only works for dynamically created receivers, not with ones registered in the manifest).

Service Broadcast Receiver Logs more than expected

My problem is that I think my service runs multiple times. The service is controlled by a switch calling a method that starts and stops the service. I have a broadcast listener inside my service and the receiver logs whenever it receives a broadcast. at first switch on, it logs two times. After switch off and on, it logs four times.
public class Service1 extends Service implements DetectionListener {
private static final String TAG = "ListenerService";
private final broadcastReceiver1 receiver = new broadcastReceiver1();
public HashMap<String, String> hashMapData;
private ARSonicManager arSonicManager;
public ListenerService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("com.digify.almostrealsonic.broadcast_intent");
registerReceiver(receiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (null != intent) {
try {
hashMapData = (HashMap<String, String>) intent.getSerializableExtra("hashMapData");
// Do something with hashMapData
} catch (Exception e) {
Log.i("onStartCommand", e.toString());
}
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onMarkerDetected(String markerKey) {
Intent intent = new Intent();
intent.putExtra("hashMapData", hashMapData);
intent.setAction("com.broadcastReceiver1_intent");
sendBroadcast(intent);
}
public static class broadcastReceiver1 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String hashMapData = intent.getStringExtra("hashMapData");
Log.i("receiver", "Got message: " + hashMapData);
}
}
}

How to stop back ground service completely..?

Hi friends i have a one problem to solve...I want to destroy the service completely, once i call onDestroy() method from Activity. But my problem is that i am unable to destroy it completely.. in background its keep on running, i am sharing the sample code what i tried..
//Activity Class
public class ServiceToAct extends Activity {
private static final String TAG = "BroadcastEvent";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(myService.BROADCAST_ACTION));
}
/*#Override
protected void onResume() {
super.onResume();
}*/
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onDestroy() {
stopService(intent);
Toast.makeText(this, "Destroy Completely", Toast.LENGTH_LONG).show();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
// service class
public class myService extends Service {
private static final String TAG = "BroadcastEvent";
public static final String BROADCAST_ACTION = "com.service.activity.myService";
private final Handler handler = new Handler();
Intent intent;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "start", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendToUI);
handler.postDelayed(sendToUI, 1000);
}
#Override
public void onDestroy() {
super.onDestroy();
stopSelf();
//stopService(intent);
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
private Runnable sendToUI = new Runnable() {
#Override
public void run() {
myData();
handler.postDelayed(this, 10000);
}
};
private void myData() {
Log.d(TAG, "keep on entering");
Toast.makeText(this, "Keep on despling in UI", Toast.LENGTH_LONG).show();
sendBroadcast(intent);
}
}
Here Actually i want to update my UI from service, Mine everything is working, but if i destroy the service its keep on calling myData() method, and i am getting the Toast msg if i close the application also.
My issue is i don't want that toast msg once the service is desroyed
I used stopService(intent) method, which destroy the service, but background method myData() is keep on calling
for stop service completely use this ..
myActivity.java
#Override
public void onDestroy() {
stopService(intent);
super.onDestroy();
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
service.java
#Override
public void onDestroy()
{
stopSelf();
super.onDestroy();
}
You'd better never call onXxx() derectly.
Use stopService(Intent i) in your activity and stopSelf() in you service to stop instead.
use stopService() method after updating UI
or
Instead of using startService use bindService in the activity. When activity destroys, service also destroys

Categories

Resources