Helle Stack community,
I created a simple app that loads a json and loads the data in a recyclerview.
The recyclerview includes cardviews.
The activity shows me a blank page if I haven't any internet connection,
but normally I want to see some blank cardviews like in the 9GAG app.
In the 9GAG app you get all data on swipe the display.
My app should load all data on internet connection is available. I googled something about broadcast receiver, but can't find a simple example for my need.
Maybe someone can show me a simple example or the way to do some action like in the 9GAG app. Info: The app is for api 21 User.
I would appreciate it.
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if (Network.isNetworkAvailable(Constants.ApplicationContext)) {
} else {
}
}
}
public class Network {
public static boolean isNetworkAvailable(Context context) {
int retriesNum = Constants.checkConnectionRetriesNum;// a number that I put as 5 for retries to make consideration for bad connections
if(context!=null)
while (retriesNum > 0) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = connectivityManager.getActiveNetworkInfo();
boolean isConnected = network != null &&
network.isConnectedOrConnecting();
if (isConnected) {
return true;
} else {
network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
isConnected = network != null && network.isConnectedOrConnecting();
if (isConnected) {
return true;
} else {
network = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
isConnected = network != null && network.isConnectedOrConnecting();
if (isConnected) {
return true;
} else {
retriesNum--;
}
}
}
}catch (Exception ex){
return true;
}
}
return false;
}
Use a BroadcastReceiver that gets notified, when the connection state changes. It is very important that you register it in your manifeset!
Add a class, similar to this to your project:
public class NetworkChangedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Network state changed!
// Check if the user connected using ConnectivityManager.getActiveNetworkInfo()
}
}
Add it to your manifest file, so the systems knows it should notify you:
<manifest>
...
<application>
...
<receiver
android:name=".NetworkChangedReceiver"
android:process=":remote">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
...
</application>
</manifest>
Edit:
From the docs:
Apps targeting Android 7.0 (API level 24) do not receive CONNECTIVITY_ACTION broadcasts if they register to receive them in their manifest, and processes that depend on this broadcast will not start. This could pose a problem for apps that want to listen for network changes or perform bulk network activities when the device connects to an unmetered network. Several solutions to get around this restriction already exist in the Android framework, but choosing the right one depends on what you want your app to accomplish.
Note: A BroadcastReceiver registered with Context.registerReceiver()
continues to receive these broadcasts while the app is running.
I didn't knew about this, so thanks to #Paul Nie for letting me know :D
I can't really help further at this point. But this seems like a good point to start some research about this topic: https://developer.android.com/topic/performance/background-optimization.html#connectivity-action
Related
Is there any way to automatically connect a specific device via Bluetooth LE on app startup?
I've been scrolling through stack overflow for the past few hours and have seen a number of similar questions, although majority are quite outdated and deal with reflections or other complex methods that I can't quite comprehend (these methods I've tried to implement, but not successfully, as I didn't really understand what was going on).
So far, I've managed to find the device by its friendly name, although I have no clue what to execute in that if statement. This is within my MainActivity:
protected void onCreate(Bundle savedInstanceState) {
...
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Bluetooth not supported",Toast.LENGTH_SHORT).show();
} else {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if(pairedDevices.size()>0){
for(BluetoothDevice device: pairedDevices){
if (deviceName.equals(device.getName())) {
//Device found!
//Now how do I pair it?
break;
}
...
Assuming you've successfully identified the BlueToothDevice, you now need to connect to the GATT(Generic Attribute Profile), which allows you to transfer data.
Use the BlueToothDevice.connectGatt method. Using the first overload, the method takes in a Context , a boolean (false = directly connect, true = connect when available), and a BlueToothGhattCallback. The callback receives info from the device.
BlueToothGatt blueToothGatt = device.connectGatt(this, false, blueToothGattCallback);
An example to implement the callback:
BluetoothGattCallback blueToothGattCallback =
new BluetoothGattCallback()
{
#Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if(newState == BlueToothProfile.STATE_CONNECTED){
/* do stuff */
}
}
}
More details on the callbacks here.
Ended up scrolling through the source code for this app, particularly the SerialSocket, SerialService and SerialListener files which completely solved my problem.
This question might be a duplicate question, but i cant find proper solution.
I have chat app in which i set function for when remote android device on background mode it will get notification by FCM when new message will come(new node added in chatroom).
So
if remote device is in the foreground mode than it will get notification by app and its has definitely internet connectivity for this i can set message delivery successfully.
if remote device is in the background mode than it will get notification by FCM and its has definitely internet connectivity. for this i can also set message delivery successfully.
So how do i check that remote device is totally offline(no internet connection) or how to check FCM is not success to send notification ?
for example:
if(messegeReceiver(remote device) has no internet connectivity )
{
//here i want to change data in firebase//
}
else
{
//here i want to change data in firebase//
}
I have "Users" node in which every users set device_token while login the app.
You can device checking offline/online mode via set one param in your chat table. When user exit or minimize application then set states to 0 and maximum set to 1.Best way if possible you use firebase real-time database for online offline.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
NetworkChangeReceiver receiver = new NetworkChangeReceiver();
regisenter code hereterReceiver(receiver, filter);
public static class NetworkChangeReceiver extends BroadcastReceiver {
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in air plan mode it will be null
return (netInfo != null && netInfo.isConnected());
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if (!isConnected) {
relativelayout_connection.setVisibility(View.GONE);
isConnected = true;
return true;
}
} else {
relativelayout_connection.setVisibility(View.VISIBLE);
}
}
}
} else {
relativelayout_connection.setVisibility(View.GONE);
isConnected = false;
return false;
}
return isConnected;
}
#Override
public void onReceive(final Context context, final Intent intent) {
// isNetworkAvailable(context);
if (isOnline(context)) {
} else {
relativelayout_connection.setVisibility(View.VISIBLE);
}
}
}
FCM does not guarantee that the push notification gets delivered. It completely depends upon various factors like internet connection (as you mentioned), OEM behavior, Doze mode etc.
In your case, you are trying to send messages via FCM from one device to another and shown messages in the form notifications just like any other chat application.
The only problem here is that the FCM does not provide you with delivery parameters in response (image attached) that you are looking for. It only gives count for number of notifications that has been accepted by the gateway i.e. FCM (success) and the count for number of notifications that has been rejected by the gateway (failure). It also gives the reason for rejection (error) message like NotRegistered, MissingRegistrationToken, etc and you can refer this for the same.
My suggestion here would be to have a handshake message in place that acknowledges the delivery of the push notification from the other device. As soon as you receive the push notification send a handshake message via FCM and that gets received by the first device which understands that the push notification has been delivered. In case if the device does not receive the handshake you assume that the message is yet to be delivered.
I hope this really helps you and please up vote the answer or accept the answer if you feel like doing so.
I would like to know if on android it is possible to get a broadcast once the user clicks the wifi disconnect button to run a method BEFORE the device disconnects from the internet , I am already using a broadcast receiver to catch network change but it is executed after internet is disconnected I am using the code below :
public class InternetReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if (isNetworkAvailable(context) && !isMyServiceRunning(MessagingService.class,context)){
Intent i = new Intent(context,MessagingService.class);
context.startService(i);
Log.e("service started ","true");
}
}
private boolean isMyServiceRunning(Class<?> serviceClass, Context c) {
ActivityManager manager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public boolean isNetworkAvailable(Context c) {
ConnectivityManager connectivityManager
= (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
I am using the code above to run the service once internet is connected but it is just an example
Edit: I assume that you want to react to the user's click on the wifi disconnect button
You could check the state of the wifi connection by using Android's WifiManager which offers some possibilities to get information about your wifi environment and connection.
Connectivity can be established or torn down, and dynamic information about the state of the network can be queried.
Source: http://developer.android.com/reference/android/net/wifi/WifiManager.html
Have a look at the following. I guess it'll be helpful to you.
WIFI_STATE_CHANGED_ACTION Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown.
int WIFI_STATE_DISABLED Wi-Fi is disabled.
int WIFI_STATE_DISABLING Wi-Fi is currently being disabled.
I just started learning Google Analytics for Android (v4). I am trying to measure how many users use my application with WiFi turned on when an activity is created. I am not sure if I am doing this correctly but I added a custom dimension for "Users are Connected" and used this code:
builder.setCustomDimension(1, isNetworkConnected() ? "True" : "False");
tracker.send(builder.setNewSession().build());
I look at the Google Analytics webpage and cannot see any information about this custom dimension on the "Realtime" navigation. I can see that the user count increased but no information about whether users are connected or not.
Thanks in advance.
Android has to check with isNetworkConnected. If the condition provided, you can run your request in this. This will assume internet is available and connected.
Implement this way:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
if(isNetworkConnected(this)){
// start a service related to internet or
// put your tracker to send data
tracker.send(builder.setNewSession().build()); // or any other methot you use to track app
}
}
public static boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected());
}
}
I am trying to develop an app where it will turn on your ringer if someone calls you a certain amount of times in a row in a certain period of time. This is my first real app, so I'm a little stuck.
How would I record whenever a call is received in an internal list? Would this need to be a service to always be running, or could this work in a normal app by just receiving the intent of the dialer app?
I apologize if this question is a little vague.
The best way to do it is, by declaring your broadcast receiver in the manifest, this will cause that the code on your BroadcastReceiver class to get executed everytime the event is fired, without the need of a service running in the background all the time, let the OS handle the observing part for you...
<receiver android:name=".ReceiverExample">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
Now, in your broadcastreceiver class "ReceiverExample", create a SharedPreference to store the number of incomming calls, and based on that, you can validate if is time to do something else or not...
public class ReceiverExample extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Logic to listen incoming calls, and keep track of them using Shared Preferences..
}
}
Services are good for long tasks but the OS it self is well suited to Monitor/Observe events (like Telephony events e.g. Incomming calls...), try not to re-do the OS work by creating Services just to monitor already known events...
Regards
use single Tone Class for recording
public class Recording {
private static MediaRecorder recorder;
private File audiofile;
private static Recording mInstance;
public MediaRecorder getRecorder() {
System.out.println("From singleton..!!!");
return recorder;
}
public static Recording getInstance(Context context) {
return mInstance == null ? (mInstance = new Recording(context))
: mInstance;
}
private Recording(Context context) {
System.out.println("Again initiated object");
File sampleDir = Environment.getExternalStorageDirectory();
try {
audiofile = File.createTempFile("" + new Date().getTime(), ".amr",
sampleDir);
} catch (IOException e) {
e.printStackTrace();
return;
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
}
}