I have 1 activity and 1 service. The service will be started when the activity comes into background and will be stopped when the activity comes into foreground. When the service stops, I want to send an object from it to the activity by intent. Here is my code
MyActivity.java
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WITH_RLM)) {
//I will get the object received by service here
}
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_lesson_ins);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_WITH_RLM);
localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}
#Override
protected void onResume() {
super.onResume();
if (intent != null) {
stopService(intent);
}
}
#Override
protected void onPause() {
super.onPause();
if (intent != null) {
startService(intent);
}
}
#Override
protected void onStop() {
super.onStop();
localBroadcastManager.unregisterReceiver(broadcastReceiver);
}
MyService.java
private RecordLessonModel recordLessonModel;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//I code sth for handle recordLessonModel object
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent(MyActivity.ACTION_WITH_RLM);
intent.putExtra(MyActivity.RECORD_MODEL_NAME, Parcels.wrap(recordLessonModel));
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
The problem here is my broadcastReceiver in MyActivity cannot receive intent from service when my activity comes to foreground. I don't know why.
Thanks.
You should consider unregistering your broadcastReceiver into onDestory() instead of onStop()
because your brodcastReceiver is getting unregistered when activity goes background.
For more look at HERE
Related
I can't stop receiving broadcasts. Why?
This is the code I have:
public class MainActivity extends AppCompatActivity {
BroadcastReceiver br = new CustomReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BroadcastReceiver br = new CustomReceiver();
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
this.registerReceiver(br, filter);
}
#Override
protected void onStart() {
super.onStart();
if(!br.isOrderedBroadcast())
this.registerReceiver(br, filter);
}
#Override
protected void onStop() {
super.onStop();
if(br.isOrderedBroadcast())
this.unregisterReceiver(br);
}
#Override
protected void onPause() {
super.onPause();
if(br.isOrderedBroadcast())
this.unregisterReceiver(br);
}
#Override
protected void onResume() {
super.onResume();
if(!br.isOrderedBroadcast())
this.registerReceiver(br, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(br.isOrderedBroadcast())
this.unregisterReceiver(br);
}
}
public class CustomReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
String toastMessage = "TOAST";
switch (intentAction){
case Intent.ACTION_POWER_CONNECTED:
toastMessage="Power Connected!";
break;
case Intent.ACTION_POWER_DISCONNECTED:
toastMessage="Power Disconnected!";
break;
}
Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();
}
}
When I go to onPause() and onStop() the app continues to show toast message of connect and disconnect charge. I don't know why.
My guess is that condition (which you're using in onPause() and onStop()) br.isOrderedBroadcast() is false so CustomReceiver won't get unregistered.
Also, according to the documentation, you should register/unregister CustomReceiver either in onCreate()/onDestroy() or in onResume()/onPause().
I'm working on an Android app in which I need to detect when user locked and unlocked, not the screen on/off. So, that I can perform certain action according locked and unlocked. But I'm unable to achieve my goal.
I declare a broadcast inside a service, register the service and receiver inside the manifest and also actions.
It's working fine, when app is open. As the app goes in background it's stop working.
public class UseService extends Service {
#Nullable
Vibrator vibr;
MediaPlayer audi;
//This is Service Class
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(receiver, filter);
}
//Broadcast Receiver
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (action.equals(Intent.ACTION_SCREEN_OFF) && myKM.inKeyguardRestrictedInputMode())
{
vibr.vibrate(500);
if( action.equals(Intent.ACTION_SCREEN_ON) && !myKM.inKeyguardRestrictedInputMode() )
{
vibr.vibrate(5000);
}
}
}
};
//************************Started*************
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
audi=MediaPlayer.create(UseService.this, R.raw.start);
Toast.makeText(UseService.this, "The Service Has Been Started",Toast.LENGTH_SHORT).show();
return START_STICKY;
}
//*******************OnDestroy****************
#Override
public void onDestroy() {
Toast.makeText(UseService.this, "The Service is Destroyed",Toast.LENGTH_SHORT).show();
unregisterReceiver(receiver);
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
Vibrator vibr;
Button btns;
//this is MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btns=(Button)findViewById(R.id.btn);
vibr=(Vibrator) getSystemService(VIBRATOR_SERVICE);
btns.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(), UseService.class);
startService(intent);
}
});
}
#Override
protected void onPause() {
super.onPause();
}
}
I have an activity. It will be receive two variable from an service. In the service, I will send two variable to the activity by
// Send first variable
sendBroadcast(new Intent("first_one"));
// Send second variable
sendBroadcast(new Intent("second_one"));
Now, In the activity, I used bellow code to receive the data. There are
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(firstRec, new IntentFilter("first_one"));
registerReceiver(secondRec, new IntentFilter("second_one"));
}
#Override
protected void onPause() {
super.onPause();
if (firstRec != null) {
unregisterReceiver(firstRec);
firstRec = null;
}
if (secondRec != null) {
unregisterReceiver(secondRec);
secondRec = null;
}
}
private BroadcastReceiver firstRec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG","OK first");
}
};
private BroadcastReceiver secondRec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG","OK second");
}
};
However, I cannot print the log "OK second" when I called sendBroadcast(new Intent("second_one")); in the service. What is happen? How can I fix it? Thank you
UPDATE: my activity is an accept calling activity get from #notz
How can incoming calls be answered programmatically in Android 5.0 (Lollipop)?. Then I create an service as following
public class myService extends Service{
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent answerCalintent = new Intent(getApplicationContext(), AcceptCallActivity.class);
answerCalintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
answerCalintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(answerCalintent);
//Send the second command after 10 second and make the calling in background
new CountDownTimer(10000, 100) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sendBroadcast(new Intent("second_one"));
}
}.start();
return START_STICKY;
}
}
You should unregister your reŃeiver in a method opposite to that in which you register it:
If you registered receiver in onCreate() - then you should unregister it in onDestroy().
But as i know, for most cases, the best practice is to register receiver in onResume() and unregister it in onPause().
In my Application I have to notify my Activity from IntentService class .
For that purpose I am using LocalBroadcastManager. But I am not receiving anything in the onReceive of my Broadcast Receiver. Here is what I have written.
In my BaseActivity I have registered my receiver.
public class BaseActivity extends FragmentActivity implements App {
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter(custom-event-name));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mMessageReceiver);
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "custom-event-name" is broadcasted.
BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
System.out.println("Overlay Message" +bundle.getString("message"));
}
};
}
I am sending a local broadcast from my RegisterAlarmIntentService class.
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
public RegisterAlramIntentService() {
super("AlarmService");
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Intent localIntent = new Intent(custom-event-name);
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
onHandleIntent() method is called. But nothing is received in onReceive() of my receiver.
Please Help. Thanks in advance!!
Try
public class RegisterAlramIntentService extends WakefulIntentService implements
APIConstants {
Intent localIntent;
public RegisterAlramIntentService() {
super("AlarmService");
localIntent = new Intent(custom-event-name);
}
#Override
public String getTag() {
return "AlarmService";
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("Working till here fine In RegisterAlarm");
Bundle bundle = intent.getExtras();
Thread.sleep(5000); // For Testing only because it is in whole new thread (which may not wait for your reciever to setup)
localIntent.putExtras(bundle );
LocalBroadcastManager.getInstance(this).sendBroadcast(
localIntent);
}
}
Also in manifest :
<service android:name="com.commonsware.android.localcast.RegisterAlramIntentService"/>
See this
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