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();
}
}
};
}
Related
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"));
}
}
}
I have the below ConnectivityReceiver class that extends BroadcastReceiver which is used to check the internet connection.
Also there is another activity SplashActivity, which implements this class for checking the internet connection. I am registering the receiver in OnCreate and unregistering it in the OnDestroy method. But still, after going to next activity, LeakCanary shows memory leak in SplashActivity.
I have instantiated LeakCanary and few methods in MyApplication class.
Please find below the screenshot of the leak.
Can someone please help me in detecting the memory leak and solving this issue?
ConnectivityReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectivityReceiver extends BroadcastReceiver
{
public static ConnectivityReceiverListener connectivityReceiverListener;
public ConnectivityReceiver()
{
super();
}
#Override
public void onReceive(Context context, Intent arg1)
{
if(arg1.getAction() != null && arg1.getAction().equalsIgnoreCase(ConnectivityManager.CONNECTIVITY_ACTION))
{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm != null)
{
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (connectivityReceiverListener != null)
connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
}
}
}
public static boolean isConnected()
{
ConnectivityManager cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm != null)
{
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
return false;
}
public interface ConnectivityReceiverListener
{
void onNetworkConnectionChanged(boolean isConnected);
}
}
MyApplication.java
import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
public class MyApplication extends Application
{
private static MyApplication mInstance;
#Override
public void onCreate()
{
super.onCreate();
mInstance = this;
if(LeakCanary.isInAnalyzerProcess(this))
return;
LeakCanary.install(this);
}
public static synchronized MyApplication getInstance()
{
return mInstance;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener)
{
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
SplashActivity.java
public class SplashActivity extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener
{
final int REQUEST_CODE_RECOVER_PLAY_SERVICES = 1001, PERMISSION_READ_STORAGE = 0;
RelativeLayout relativeLayout;
IntentFilter intentFilter;
ConnectivityReceiver connectivityReceiver;
Bitmap thumbnail;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
Fabric.with(this, new Crashlytics());
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
connectivityReceiver = new ConnectivityReceiver();
registerReceiver(connectivityReceiver, intentFilter);
if(checkInternet())
{
Intent mainIntent = new Intent(SplashActivity.this, WelcomeActivity.class);
SplashActivity.this.startActivity(mainIntent);
SplashActivity.this.finish();
}
}
boolean checkInternet()
{
boolean isConnected = ConnectivityReceiver.isConnected();
showSnack(isConnected);
return isConnected;
}
private void showSnack(boolean isConnected)
{
Snackbar snackbar = Snackbar.make(relativeLayout, AppConfig.noInternet, Snackbar.LENGTH_INDEFINITE);
if(!isConnected)
{
snackbar.setAction("GO OFFLINE", new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent mainIntent = new Intent(SplashActivity.this, WelcomeActivity.class);
SplashActivity.this.startActivity(mainIntent);
SplashActivity.this.finish();
}
});
View sbView = snackbar.getView();
TextView textView = sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.setActionTextColor(getResources().getColor(R.color.colorPrimary));
snackbar.show();
}
else
snackbar.dismiss();
}
#Override
public void onDestroy() {
unregisterReceiver(connectivityReceiver);
connectivityReceiver = null;
super.onDestroy();
}
#Override
public void onPause()
{
super.onPause();
}
#Override
public void onResume()
{
super.onResume();
MyApplication.getInstance().setConnectivityListener(this);
}
#Override
public void onNetworkConnectionChanged(boolean isConnected)
{
showSnack(isConnected);
}
}
you need to unregisterReceiver(connectivityReceiver); receiver in onPause() or onStop();because onDestroy(); will not called until the Activity in stack of Activities. onDestroy(); will called when you will finish the Activity and unregisterReceiver(connectivityReceiver); will be excuted.
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");
}
}
}
I'm going through the Facebook Android SDK (https://developers.facebook.com/docs/facebook-login/android) and am finding it difficult to understand. I simply want to open a new activity after (successful) login, though the steps show alot of other code and I'm not sure which ones I require. Here's my code:
activity_main.xml
<com.facebook.login.widget.LoginButton
android:id="#+id/fb_login_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
tools:layout_editor_absoluteY="496dp" />
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button or_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
or_email = (Button)findViewById(R.id.or_email);
or_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
MainActivity.this.startActivity(i);
}
});
}
}
Register.java (for blank activity_register.xml)
public class Register extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
}
}
So basically, I just want to open activity_register.xml after successfully logging in. So i'd imagine I add a new Intent under the onSuccess() method. However I'm not sure where exactly I'm supposed to put this code, and also whether it needs the previous code block (the FragmentActivity) in order to work. So If someone could explain to me how each of those 3 code blocks are working in detail. that would be great.
ps: I've already registered my app id and all that so the button is working, I just want it to open a new activity after logging in. Right now it just goes back to activity_main after logging in.
Edit: Following code doesn't open up activity_register, it just goes back to activity_main
public class MainActivity extends AppCompatActivity {
Button or_email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager mFacebookCallbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
LoginButton mFacebookSignInButton = (LoginButton)findViewById(R.id.fb_login_btn);
mFacebookSignInButton.registerCallback(mFacebookCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
//TODO: Use the Profile class to get information about the current user.
Intent intent = new Intent(MainActivity.this, Register.class);
startActivity(intent);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
);
or_email = (Button)findViewById(R.id.or_email);
or_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
MainActivity.this.startActivity(i);
}
});
}
}
Try this:
in your activity: Make sure you do
Initilize facebook sdk and accessTokenTracker in onCreate()
Give permission in your login Button and register the callback.
In onSuccess() method start new Activity
Finally override the onActivityResult() method and add the callbackManger.onActivityResult() with the request code.
public class MainActivity extends AppCompatActivity {
Button or_email;
CallbackManager mFacebookCallbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker mProfileTracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
mFacebookCallbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
accessTokenTracker.startTracking();
LoginButton mFacebookSignInButton = (LoginButton)findViewById(R.id.fb_login_btn);
mFacebookSignInButton.setReadPermissions(Arrays.asList(
"public_profile", "email", "user_birthday", "user_friends"));
mFacebookSignInButton.registerCallback(mFacebookCallbackManager, callback);
or_email = (Button)findViewById(R.id.or_email);
or_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Register.class);
MainActivity.this.startActivity(i);
}
});
}
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
try {
if (Profile.getCurrentProfile() == null) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile_old, Profile profile_new) {
profile = profile_new;
Log.v("facebook - profile", profile_new.getFirstName());
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
} else {
profile = Profile.getCurrentProfile();
Log.v("facebook - profile", profile.getFirstName());
}
Intent intent = new Intent(getApplicationContext(), Register.class);
startActivity(intent);
finish();
} catch (Exception e) {
Log.d("ERROR", e.toString());
}
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_LONG).show();
}
#Override
public void onError(FacebookException e) {
Log.d("FACEBOOK ERRROR", e.toString());
Toast.makeText(getApplicationContext(), "Something went wrong!! Please try again", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
mFacebookCallbackManager.onActivityResult(requestCode, responseCode, intent);
}
}
in manifest:
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
Make sure your add the app_id in manifest...
Add this code inside onCreate() method
FacebookSdk.sdkInitialize(getApplicationContext());
CallbackManager mFacebookCallbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
LoginButton mFacebookSignInButton = (LoginButton)findViewById(R.id.fb_login_btn);
mFacebookSignInButton.registerCallback(mFacebookCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
//TODO: Use the Profile class to get information about the current user.
Intent intent = new Intent(MainActivity.this, Register.class);
startActivity(intent);
}
#Override
public void onCancel() {
Toast.makeText(getApplicationContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
}
);
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);
}