How to update the UI with BroadcastReceiver onReceive in Android? - java

I want to update the UI according to the WiFi status in my Android app in Java. I am unable to update the UI to show the new string. Please help me.
Here is my code
public class MainActivity extends AppCompatActivity {
IntentFilter intentFilter = new IntentFilter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new NetworkConnectionReceiver(), intentFilter);
TextView displayStatus = findViewById(R.id.displayStateTextView);
}
}
class NetworkConnectionReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Log.i("MyReceiver", Boolean.toString(wifiManager.isWifiEnabled()));
}
}

Use this code:
public class MainActivity extends AppCompatActivity {
...
BroadcastReceiver br = new BroadcastReceiver(){
#Override
public void onReceive( Context context, Intent intent ){
//update UI here directly
View view = findViewById( R.id.example );
}
};
#Override
protected void onResume(){
super.onResume();
// Check state here
...
IntentFilter filter = new IntentFilter();
filter.addAction( ConnectivityManager.CONNECTIVITY_ACTION );
registerReceiver( br, filter);
}
#Override
protected void onPause(){
super.onPause();
unregisterReceiver( br );
}
...
}

You can do it using interface
interface WifiStateListener{
void onStateChanged(Boolean enabled);
}
Then add a constructor to pass the WifiStateListener to BroadcastReceiver
class NetworkConnectionReceiver extends BroadcastReceiver {
private WifiStateListener mWifiStateListener;
public NetworkConnectionReceiver(WifiStateListener wifistateListener){
mWifiStateListener = wifistateListener;
}
#Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if(mWifiStateListener != null){
mWifiStateListener.onStateChanged(wifiManager.isWifiEnabled());
}
Log.i("MyReceiver", Boolean.toString(wifiManager.isWifiEnabled()));
}
}
And in Activity, while registering receiver you can pass the interface
registerReceiver(new NetworkConnectionReceiver(enabled -> {
//do based on wifi state change
}), intentFilter);
Other options are to use EventBus, Observables etc

You can user LocalBroadCastManager.
First write broadCastReceiver in activity
register that broadcast with LocalBroadCastManager in onResume
unregister that broadcast with LocalBroadCastManager in onPause as well
than write Broadcast of internet connection and call LocalBroadCastManager which you register in activity
private BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction() == "local_broadcast_update_UI"){
updateUI()
}
}
};
#Override
protected void onResume(){
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver( broadCastReceiver, new
IntentFilter("local_broadcast_update_UI"));
}
#Override
protected void onPause(){
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver("local_broadcast_update_UI");
}
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable() || mobile.isAvailable()) {
LocalBroadcastManager.getInstance(context).sendBroadcast(new
Intent("local_broadcast_update_UI"));
}
}
}

Related

Toggle Background/Foreground Modes

I'm trying to make it so that when you press the power button to turn off the android, my app goes into background mode. When you press the power button to turn on the android, my app should go into foreground mode.
The error I get is:
java.lang.RuntimeException: Error receiving broadcast Intent {
act=android.intent.action.SCREEN_ON flg=0x50000010 }
The error comes from the intent with FLAG_ACTIVITY_CLEAR_TOP
Here's the MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver(MainActivity.this, this);
registerReceiver(mReceiver, filter);
moveTaskToBack(true);
}
}
Here's the BroadcastReceiver:
public class ScreenReceiver extends BroadcastReceiver {
MainActivity mainAct;
Context ctx;
public ScreenReceiver(MainActivity act, Context con) {
mainAct = act;
ctx = con;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mainAct.moveTaskToBack(true);
System.out.println("OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Intent i = new Intent(ctx, ScreenReceiver.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAct.startActivity(i);
System.out.println("ON");
}
}
}
I'm using code from the following tutorial:
https://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
The mistake was passing ScreenReceiver.class instead of MainActivity.class into the intent. Here's the corrected version:
public class ScreenReceiver extends BroadcastReceiver {
MainActivity mainAct;
Context ctx;
public ScreenReceiver(MainActivity act, Context con) {
mainAct = act;
ctx = con;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
mainAct.moveTaskToBack(true);
System.out.println("OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Intent i = new Intent(ctx, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mainAct.startActivity(i);
System.out.println("ON");
}
}
}

How to close an Activity using push Notification in Firebase?

I am working on Firebase Push Notification and i want to close MainActivity. Application should finish when onMessageReceived() is called. I am also passing the Context but its not working. In this case, I'll send notification when application is opend. My code:
MainActivity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new FirebaseMessagingService(MainActivity.this);
}
}
FirebaseMessagingService.java
public class FirebaseMessagingService extends
com.google.firebase.messaging.FirebaseMessagingService {
Context context;
public FirebaseMessagingService(Context ctx) {
this.context = ctx;
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
context.finish();
}
}
You could define a BroadcastReceiver in MainActivity, that calls finish() when triggered:
private final BroadcastReceiver finishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
Register/unregister it when appropriate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ...
LocalBroadcastManager.getInstance(getApplicationContext())
.registerReceiver(finishReceiver,
new IntentFilter(FirebaseMessagingService.ACTION_FINISH));
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(getApplicationContext())
.unregisterReceiver(finishReceiver);
super.onDestroy();
}
And then you just simply have to send a local broadcast from onMessageReceived():
public static final String ACTION_FINISH = "yourpackagename.ACTION_FINISH";
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
LocalBroadcastManager.getInstance(getApplicationContext())
.sendBroadcast(new Intent(ACTION_FINISH));
}
(FirebaseMessagingService is a Context subclass, there is no need to pass another Context instance to it)

Updating RecyclerView with adapter.notifyDataSetChanged()

I've implemented a RecyclerView which has a user interface of a timer counting down. I created a BroadcastService class which creates a CountDownTimer and broadcasts the timer's contents in the onTick() method to my MainActivity, where I use a BroadCast receiever to update the UI.
My BroadcastReceiver is only receiving the initial value from the BroadcastService. I figured that's because I hadn't notified the recycler view's adapter that the data had changed. However, because of variable scope, I'm unable to access my adapter from my broadcast receiver.
Perhaps I have a fundamental lack of understanding of variable scope, but how can I access the adapter from
adapter = new DataAdapter(getApplicationContext(), data);
in my broadcast receiver class? Because right now it's not being recognized.
This is my class definition + onCreate()
public class Profile_Page extends ActionBarActivity implements DataAdapter.ClickListener {
private RecyclerView recyclerView;
public DataAdapter adapter;
private Context context;
String currentUser;
Data current = new Data();
final List<Data> data = new ArrayList<>();
public static String BROADCAST_ACTION =
"packagename.countdown_br";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(br, filter);
startService(new Intent(this, Broadcast_Service.class));
setContentView(R.layout.activity_profile__page);
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.whereEqualTo("author", ParseUser.getCurrentUser());
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if (e == null) {
for (ParseObject getData : list)
{
current.1= getData.getString("1");
current.2= getData.getString("2");
current.3= getData.getString("3");
current.4= getData.getString("4");
current.5= getData.getString("5");
data.add(current);
}
}
else {
}
adapter = new DataAdapter(getApplicationContext(), data);
recyclerView.setAdapter(adapter); //set recyclerView to this adapter
}
});
}
And here's my Broadcast Receiver code [which is also in MainActivity.java]
public BroadcastReceiver br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateGUI(intent);
//HOW TO NOTIFY DATA SET CHANGE
}
};
public void updateGUI(Intent intent) {
if (intent.getExtras() != null) {
long millisUntilFinished = intent.getLongExtra("countdown", 0);
current.goalTimer = String.valueOf(intent.getExtras().getLong("countdown") / 1000);
}
}
And, if it is of any use, here's my Broadcast Service class:
public class Broadcast_Service extends Service {
private final static String TAG = "BroadcastService";
LocalBroadcastManager broadcastManager;
public static final String COUNTDOWN_BR = "packagename.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Starting timer...");
cdt = new CountDownTimer(30000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
#Override
public void onFinish() {
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 intent) {
return null;
}
}
First of all, extend the BroadcastReciever class as follows:
public class MyReciever extends BroadcastReciever{
private Profile_Page activity;
public MyReciever(Profile_Page activity){
this.activity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
activity.updateGUI(intent);
}
}
Create a static instance of your activity and pass it to your receiver.
public class Profile_Page extends ActionBarActivity implements DataAdapter.ClickListener {
private static Profile_Page instance;
private MyReciever myReceiver;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
myReceiver = new MyReciever(instance);
...
}
public void updateGUI(Intent intent) {
...
}
}
Now you can access your adapter quite easily. Hope this helps.

BroadcastReceiver Wifi disabled

I want my application to give a notification when wifi goes 'offline'.
I figured out the notification part. But I can't seem to figure out the 'wifi check'-part.
I read something about BroadcastReceiver but I can't seem to get it working. Any useful links? or example code? Tutorials?
Thanks in advance!
Updated with code. Its working but I need it to only give a notification when wifi goes offline.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
setContentView(R.layout.activity_main);
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if(currentNetworkInfo.isConnected()){
}else{
showNotification();
}
}
};
You can try something like this
In Manifest.xml
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
In your application Code:
public class BroadCastSampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if(currentNetworkInfo.isConnected()){
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
}
}
};
}

how to extract the string value in Android services from an activity?

how to extract the string value in Android services from an activity?
My activity has a edit text, the entered string must be received in my services.
TempLaunch.java :
public class TempLaunch extends Activity {
private EditText text;
private Button okbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.templaunch);
addListenerOnButton();
}
public void addListenerOnButton() {
text = (EditText) findViewById(R.id.edittext_newid);
okbtn = (Button) findViewById(R.id.button_newid);
okbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TempLaunch.this, "In Temp launch class ",Toast.LENGTH_SHORT).show();
Toast.makeText(TempLaunch.this, text.getText(),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
Toast.makeText(TempLaunch.this, "I am in Main activity class ",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
});
Intent i = new Intent(this, MusicService.class);
i.putExtra("DD_URL", text.getText().toString());
//startActivity(i);
}
}
MusicService.java
public class MusicService extends Service {
#Override
public void onCreate() {
super.onCreate();
String url = null;
Intent intent = getIntent();
String id = intent.getStringExtra("DD_URL");
System.out.println("Rosh :" + id);
Toast.makeText(MusicService.this, "I am in Service:"+ id,Toast.LENGTH_SHORT).show();
...
Please help me out with this regard.
Thanks in advance
You may use sendBroadcast(intent); which will broadcast the EditText from your Activity A.
Then you need to call onReceive(Context context, Intent intent) within your Service class. This method is called when the BroadcastReceiver is receiving an Intent broadcast, in your case will be sent from Activity A.
private final BroadcastReceiver receiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// Do something
}
};
//Register your receiver in onResume:
#Override
protected void onResume()
{
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("SOME_ACTION");
registerReceiver(receiver, filter);
}
//Unregister the receiver in onPause:
#Override
protected void onPause()
{
super.onPause();
unregisterReceiver(receiver);
}

Categories

Resources