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());
}
}
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.
I've integrated UnityAds on my Android app (that is not published yet).
I get app id and placement id from database on my server.
App id and placement id are correct, I've copied and pasted about 30 times for be sure of it.
So, when I try to get an ad in test mode, it give me the INVALID_ARGUMENT error.
Here an explaination of the error code by Unity, but as you can see it is a little generic.
I have an object that simply represents an ad service (like admob, FAN, inmobi etc)
In this case the object is called advert, and here it's how I show an ad with Unity:
protected void showUnity(){
UnityAds.initialize(this, advert.getApiKey(), true); //advert.getApiKey() returns the app id
UnityAds.addListener(new IUnityAdsListener() {
#Override
public void onUnityAdsReady(String s) {
Log.i(TAG, "onUnityAdsReady "+s);
if(s.equals(advert.getUnitId()) && !unityReady)
UnityAds.show(ActivityAd.this, advert.getUnitId()); //advert.getUnitId() returns the placement id
}
#Override
public void onUnityAdsStart(String s) {
Log.i(TAG, "onUnityAdsStart "+s);
unityReady = true;
}
#Override
public void onUnityAdsFinish(String s, UnityAds.FinishState finishState) {
if (finishState.compareTo(UnityAds.FinishState.COMPLETED) == 0) {
onAdReward(); //my callback for reward
} else if (finishState.compareTo(UnityAds.FinishState.SKIPPED) == 0) {
onAdClosed(); //my callback for ad close
} else if (finishState.compareTo(UnityAds.FinishState.ERROR) == 0) {
onAdError(finishState.toString()); //my callback for errors
}
}
#Override
public void onUnityAdsError(UnityAds.UnityAdsError unityAdsError, String s) {
onAdError(unityAdsError.toString()); //my callback for errors, here results INVALID_ARGUMENT error
}
});
}
Does anyone know what is wrong? Thanks in advance
If you check the callback closely the onUnityAdsError has 2 params, first provides the error code and the second param provides you information about what went wrong.
#Override
public void onUnityAdsError(UnityAds.UnityAdsError unityAdsError, String reason) {
onAdError(unityAdsError.toString()); //my callback for errors, here results INVALID_ARGUMENT error
}
So just check the reason and you should be able to find out what is going wrong in your integration.
Here are some methods which you can follow to solve this INVALID_ARGUMENT problem
1. Make sure you are implementing the right Initialization code in your app. There are 2 types of Initialization.
Only Unity ads Initialization
Mediation Initialization
and both methods have their own banner, interstitial, and rewarded ad code.
2. Make sure you enable test mode as Boolean. (i.e: private Boolean testMode = true;) (make sure to do false this before publish on store)
3. You can add your mobile phone as a test device to get test ads on your phone forcefully. for this, you have to first copy the Ad ID of your device. For that, go to your mobile settings > Google > Ads > This device's advertising ID. copy that ID and go to unity dashboard > Monetization > Testing > Add Test Device. Add your device Ads ID here with any name, and now you will be able to see test ads on the device.
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.
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
i would like to ask:
I have in my AppHelper class following method which check availability of internet connection.
public boolean checkInternetConnection(Context ctx) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
Log.i(GlobalApplication.APP_LOG_NAMESPACE, "Internet Connection Not Present");
return false;
}
}
Im trying to get Boolean value by using:
// check internet connection and availability
Boolean isConnectionAvailable = appHelper.checkInternetConnection(getBaseContext());
But unfortunately i get always null pointer exception. Is it matter of passed application context? And how should i solve that issue?
Thanks for any advice.
I'm going to take a stab in the dark and say that AppHelper class is a seperate Activity that is never properly started with an intent.
If this is so, I would instead implement AppHelper as a Service instead of an Activity, as the method "checkInternetConnection" is better suited for this type of task.
Weather or not the service runs in its own process or not I suppose would depend on the particular problem at hand.