Reputation: 322
I am having trouble implementing the opt-out preference for Google Analytics on Android. I am using Analytics v4. I have the preference screen working but it does not seem to prevent information being sent to Google Analytics when I uncheck the box. Do I need to check the opt-out preference in each activity or am I missing something in my PreferenceActivity?
Here is my code so far.
package edu.ncsu.oncampus;
import com.google.android.gms.analytics.GoogleAnalytics;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
public class Settings extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("trackingPreference")) {
GoogleAnalytics.getInstance(getApplicationContext()).setAppOptOut(sharedPreferences.getBoolean(key, true));
}
}
}
Upvotes: 0
Views: 1055
Reputation: 322
I was able to resolve this problem. I ended up using a two step process for the solution. The first step was to register the preference change in the Settings page I created. (Note that I used a checkbox setting for this, so I had to use the opposite value of the checkbox to set the opt-out value.) I have posted only the relevant code here.
Settings.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
SharedPreferences userPrefs = PreferenceManager.getDefaultSharedPreferences(this);
userPrefs.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener () {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,String key)
{
if (key.equals("trackingPreference")) {
GoogleAnalytics.getInstance(getApplicationContext()).setAppOptOut(!sharedPreferences.getBoolean(key, false));
}
}
});
}
I also check the setting in the main activity when I launch the app and set the opt out setting.
HomeActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
SharedPreferences userPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isOptedOut = userPrefs.getBoolean("trackingPreference", false);
GoogleAnalytics.getInstance(this).setAppOptOut(!isOptedOut);
}
Upvotes: 1