I have a broadcast receiver to check the internet connectivity, in which i have validated if no internet connection I am displaying an error screen through intent. Now i need to close the error screen when the network is reconnected and display the previous screen from which the network was gone.
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
isConnected = intent.getBooleanExtra(ConnectionDetector.CONNECTED_KEY, false);
if(isConnected){
System.out.println("A1");
finish();
}
if (intent.getAction().equals(CONNECTION_BROADCAST_ACTION)) {
System.out.println("A2");
No_Network.this.finish();
}
}
};
This is my code inside the error screen activity. How to close the activity here? finish() is not working.
How to close the activity here? finish() is not working
It is "not working" because you are not using it correctly. The correct approach is to notify the activity and tell it to finish() itself. You can do that by sending intent with "magic" code of yours directly to your activity (if it is in singleTop launch mode then startActivity() + onNewIntent() would suffice). Alternatively use event bus for communication.
Related
My application only have MainActivity with a ImageView.
BroadcastReceiver works. The Toast Message is displayed When I connect USB.
Now, I need start my application minimized and show the application only the USB cable was connected.
BroadcastReceiver broadcast_reciever = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
if (action.equals("usb_detect")) {
Toast.makeText(arg0,"Atenção!",Toast.LENGTH_SHORT).show();
finish();
startActivity(getIntent());
//startActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER));
}
}
};
Manifest is here: https://i.stack.imgur.com/sa3Pe.jpg
To bring your application to the foreground, add the following to onReceive():
Intent launchIntent = getPackageManager().
getLaunchIntentForPackage("your.package.name");
startActivity(launchIntent);
This will not start a new Activity, it will simply bring the existing task containing your application to the foreground in whatever state it was in when it got moved to the background.
Also, remove the call to finish() from your BroadcastReceiver. finish() is only used on an Activity.
I have two buttons -start and stop service buttons- in the fragment. In the initial state start button is enabled and stop button is disabled. When i click "start button",buttons states are changed. -It means start button is disabled and stop button is enabled. In the service i check gps state. If the gps is disabled, i call stopself method to destroy service. After calling stopself method, I wanna change buttons states in the fragment. But i didn't find any solution. How can i do this?
You can use below option.
In your fragment.
//In your on Create method
IntentFilter updateState = new IntentFilter();
updateState.addAction("UPDATE_BUTTON_STATE");
registerReceiver(updateStatueReceiver, updateState);
private BroadcastReceiver updateStatueReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("UPDATE_BUTTON_STATE")) {
// Here you can update your button state
}
}
};
//unregister Receiver in on Destroy method
unregisterReceiver(updateStatueReceiver);
In your Service Class
You can send broadcast using this code
Intent broadCastIntent = new Intent();
broadCastIntent.setAction("UPDATE_BUTTON_STATE");
sendBroadcast(broadCastIntent);
When my service is running and I can see my app on the screen, everything works fine. My service sends broadcast messages and I can see them in my "MainActivity". But as soon as I push the home button and my app is no longer in the foreground, it stops. The service is still running but the broadcasts don't arrive at my "dead" or "pausing" app. This is my code:
Main Activity:
onCreate:
Intent intent = new Intent(getApplicationContext(), MainGate_Service.class);
startService(intent);
#Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver(ServiceReceiver, new IntentFilter("MainGate_ring"));
}
#Override
protected void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(this).unregisterReceiver(ServiceReceiver);
}
private BroadcastReceiver ServiceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("ServiceMessage");
if(message != null) {
if(alarmActive && message.equals("ring"))
new soundPlayer().execute();
}
setNoti(message);
}
}
Service:
#Override
protected void onHandleIntent(Intent intent) {
ring = rcv_ring();
Intent ServiceIntent = new Intent("MainGate_ring");
ServiceIntent.putExtra("ServiceMessage", ring);
LocalBroadcastManager.getInstance(this).sendBroadcast(ServiceIntent);
}
whenever you press home button onStop gets call and there you are unregister receiver so there is not broadcast receiver who can receive broadcast.
LocalBroadcastManager.getInstance(this).unregisterReceiver(ServiceReceiver);
Remove above line from onStop() or unregister it whenever your service stop.
onStop#LocalBroadcastManager.getInstance(this).unregisterReceiver(ServiceReceiver);
literally unregister receiver. So there is no receiver to receive broadcasted message from service.
The problem is here
#Override
protected void onStop() {
super.onStop();
LocalBroadcastManager.getInstance(this).unregisterReceiver(ServiceReceiver);
}
Activity.onStart() :
Called after onCreate(Bundle) — or after onRestart() when the activity had been stopped, but is now again being displayed to the user. It will be followed by onResume().
Activity.onStop()
Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity.
So as soon as you leave your activity onStop() is called and you unregister your receiver.
Don't put your unregister code in onDestroy() either, because it may or may not be called and the Activity might be killed without calling it.
As suggested by #Naveen Dissanayake you might want to reconsider your logic.
You register your BroadcastReceiver inside activity, so, it will depend on Activity's lifecycle. When you press back button, activity goes into 'stopped' state - methods onPause and onStop is called. Android can also destroy this activity in it is low on resources.
Service, on the other hand, i smeant to be running inndefinetely, even when ui is not ready. If you wanat to receive notifications from Activity, there is two
possible solutions:
- Create, store and manage BroadcastReceiver in Application instance - Application class is still running until your app is destroyed. It seems like you want to play sound when service notify you about some action.
Register BroadcastReceiver in onCreate and unregister in onDestroy in notifications.
- Another solution - use another Service if you want to trigger some action or IntentService, reacting to that broadcast.
I woud consider solution - create some ResponseService, start it along with your MainGate_Service (from Application) and stop it from application too. In that Service register BroadcastReceiver or, add IntentFilter into manifest if you want it to start even when app is not running. In your Activity, bind to that service. Serive will know if some UI is attached (if Activity is bound), and, if it is, will notify activity. If it don't - will do some other things (perhaps, show notification)
If you want to receive Broadcast even if your Activity is in
Background then,
Register in onCreate(...)
#Override
protected void onCreate(Bundle sis) {
super.onCreate(sis);
setContentView(...);
LocalBroadcastManager.getInstance(this).registerReceiver(ServiceReceiver, new IntentFilter("MainGate_ring"));
}
Unregister in onDestroy()
#Override
protected void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(this).registerReceiver(ServiceReceiver, new IntentFilter("MainGate_ring"));
}
I have problem when I control Activity UI from service. It doesn't work.
class MainActivity
public void showNotice() {
Log.d("log", "can't connect to server");
tvText.setText(notice);
tvTex.setVisibility(View.VISIBLE);
pbDialog.hide();
}
I call showNotice method in my service:
((MainActivity) mContext).showNotice();
But it only show log "can't connect to server".
tvText doesn't change anything, not change text, not visible. pbDialog does'n hide?
Can i help me resolve it? Many thanks.
A service runs in its own background thread, the UI can be modified only from the UI Thread which is pretty much with the main activity.
You can try doing this, you can broadcast an event from the service when you want to hide the dialog box. Have a broadcast listener registered for this which would handle the UI modification. You should probably be using a LocalBroadcastManager and give your broadcast a unique name.
In your mainActivity, use
registerReceiver(<receiver instance>, <broadcast name>)
in the onStart or onCreate method.
This will setup your mainActivity to listen to the broadcasts, next you need to define your broadcast receiver which is the in the above register call.
BroadcastReceiver receiver;
receiver = new BroadcastReceiver() {
public void onReceive(Context c, Intent i) {
//Modify the UI, in this case hide the dialog box.
}
}
I have 1 service about mqtt receiver. When application receive message from mqtt server, it will start newA activity. this newA activity work fine but the problem is if I started newA activity before i receive message, nothing gonna happen. I tried
private newA na;
public void MessageArrive {
na.onDestroy(); //on newA activity onDestroy() is contain finish();
Intent runs = new Intent(getBaseContext(), newA.class);
runs.putExtra("data", arrMsg);
runs.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(runs);
}
but it's not work.
have any idea?
thanks in advance.
try use boardcast and on receive to listen boardcast should solve this problem.
You can override onNewIntent in your activity