I want to get users Advertising ID programmatically.I used the below code from the developer site.But its not working
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (IOException e) {
// Unrecoverable error connecting to Google Play services (e.g.,
// the old version of the service doesn't support getting AdvertisingId).
} catch (GooglePlayServicesNotAvailableException e) {
// Google Play services is not available entirely.
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final String id = adInfo.getId();
final boolean isLAT = adInfo.isLimitAdTrackingEnabled();
How can I get user's advertising id programmatically ?? please help me
I might be late but this might help someone else!
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (NullPointerException e){
e.printStackTrace();
}
return advertId;
}
#Override
protected void onPostExecute(String advertId) {
Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
}
};
task.execute();
Get GAID(Google’s advertising ID)
1. Download latest Google Play Services SDK.
2. Import the code and add it as a library project.
3. Modify AndroidManifest.xml.
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
4. Enable ProGuard to shrink and obfuscate your code in project.properties this line
proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
5. Add rules in proguard-project.txt.
-keep class * extends java.util.ListResourceBundle {
protected Object[][] getContents(); }
-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
public static final *** NULL; }
-keepnames #com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
#com.google.android.gms.common.annotation.KeepName *;
}
-keepnames class * implements android.os.Parcelable {
public static final ** CREATOR;
}
6. Call AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext()).getId() in a worker thread to get the id in String.
as like this
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (Exception e){
e.printStackTrace();
}
return advertId;
}
#Override
protected void onPostExecute(String advertId) {
Toast.makeText(getApplicationContext(), advertId, Toast.LENGTH_SHORT).show();
}
};
task.execute();
Enjoy!
or
https://developervisits.wordpress.com/2016/09/09/android-2/
You can call the below function in onCreate(Bundle savedInstanceState) of the activity
and in the logcat search for UIDMY then it will display the id like : I/UIDMY: a1cf5t4e-9eb2-4342-b9dc-10cx1ad1abe1
void getUIDs()
{
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(SplashScreen.this);
String myId = adInfo != null ? adInfo.getId() : null;
Log.i("UIDMY", myId);
} catch (Exception e) {
Toast toast = Toast.makeText(context, "error occurred ", Toast.LENGTH_SHORT);
toast.setGravity(gravity, 0,0);
toast.show();
}
}
});
}
Just in case someone is interested in trying out the fetching AdvertisingId part while Rx-ing then this might be helpful.
private void fetchAndDoSomethingWithAdId() {
Observable.fromCallable(new Callable<String>() {
#Override
public String call() throws Exception {
return AdvertisingIdClient.getAdvertisingIdInfo(context).getId();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<String>() {
#Override
public void call(String id) {
//do what you want to do with id for e.g using it for tracking
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable throwable) {
throwable.printStackTrace();
}
});
}
The modern way is to use Coroutines in Kotlin, since AsyncTask is now being deprecated for Android. Here is how I did it:
import com.google.android.gms.ads.identifier.AdvertisingIdClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class AdvertisingInfo(val context: Context) {
private val adInfo = AdvertisingIdClient(context.applicationContext)
suspend fun getAdvertisingId(): String =
withContext(Dispatchers.IO) {
//Connect with start(), disconnect with finish()
adInfo.start()
val adIdInfo = adInfo.info
adInfo.finish()
adIdInfo.id
}
}
When you are ready to use the advertising ID, you need to call another suspending function:
suspend fun applyDeviceId(context: Context) {
val advertisingInfo = AdvertisingInfo(context)
// Here is the suspending function call,
// in this case I'm assigning it to a static object
MyStaticObject.adId = advertisingInfo.getAdvertisingId()
}
Fetch the advertising id from background thread:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
String adId = adInfo != null ? adInfo.getId() : null;
// Use the advertising id
} catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
// Error handling if needed
}
}
});
I added null checks to prevent any crashes. The Google example implementation code would crash with a NullPointerException if an exception occures.
With OS validation.
Call this in an AsyncTask
/** Retrieve the Android Advertising Id
*
* The device must be KitKat (4.4)+
* This method must be invoked from a background thread.
*
* */
public static synchronized String getAdId (Context context) {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
return null;
}
AdvertisingIdClient.Info idInfo = null;
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(context);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String advertId = null;
try{
advertId = idInfo.getId();
}catch (NullPointerException e){
e.printStackTrace();
}
return advertId;
}
If you are using Kotlin use this to get the Google Advertising ID of the device
CoroutineScope(Dispatchers.IO).launch {
var idInfo: AdvertisingIdClient.Info? = null
try {
idInfo = AdvertisingIdClient.getAdvertisingIdInfo(applicationContext)
} catch (e: GooglePlayServicesNotAvailableException) {
e.printStackTrace()
} catch (e: GooglePlayServicesRepairableException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
var advertId: String? = null
try {
advertId = idInfo!!.id
} catch (e: NullPointerException) {
e.printStackTrace()
}
Log.d(TAG, "onCreate:AD ID $advertId")
}
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesAvailabilityException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
String AdId = adInfo.getId();
You need add gms libs otherwise you cannot get the advertising id. It can be reset by user or when you do a factory reset (at factory reset time the Android id also reset).
Make sure you have added play identity services, then you can get advertising id by running a thread like this:
Thread thread = new Thread() {
#Override
public void run() {
try {
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
String advertisingId = adInfo != null ? adInfo.getId() : null;
} catch (IOException | GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException exception) {
exception.printStackTrace();
}
}
};
// call thread start for background process
thread.start();
You only need this package:
implementation("com.google.android.gms:play-services-ads-identifier:17.0.0")
It's not really listed anywhere but it's published on Mavne.
Get Google Services using
GoogleApiAvailabilityLight.getInstance
You need to run your code using Async Task
try this
Using the new Android Advertiser id inside an SDK
Using Kotlin & RxJava Observers
Import in your Gradle file
implementation 'com.google.android.gms:play-services-ads:15.0.0'
Import on top of your kotlin source file
import io.reactivex.Observable
import com.google.android.gms.ads.identifier.AdvertisingIdClient
Implement a helper function
private fun fetchAdIdAndThen(onNext : Consumer<String>, onError : Consumer<Throwable>) {
Observable.fromCallable(Callable<String> {
AdvertisingIdClient.getAdvertisingIdInfo(context).getId()
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(onNext, onError);
}
Then
fetchAdIdAndThen(Consumer<String>() {
adId ->
performMyTaskWithADID(activity, 10000, adId);
}, Consumer<Throwable>() {
throwable ->
throwable.printStackTrace();
performMyTaskWithADID(activity, 10000, "NoADID");
})
Related
I try to implement the recommendation made in item #11 of issue 111316656 that says:
You should also be able to use reflection to get access to the FloatingActionButtonImpl backing the fab, and then call setImageMatrixScale(1) on that instance.
with the following code:
FloatingActionButton fab;
...
Method method = null;
try {
method = fab.getClass().getMethod("setImageMatrixScale", null);
method.invoke(fab, 1);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
But the NoSuchMethodException is raised. What is the problem?
Try like here
BluetoothGatt localBluetoothGatt = gatt;
java.lang.reflect.Method localMethod = localBluetoothGatt.getClass().getMethod("refresh", new Class[0]);
if (localMethod != null) {
boolean bool = ((Boolean) localMethod.invoke(localBluetoothGatt, new Object[0])).booleanValue();
return bool;
}
With the help of Mike M. (see comments in the question), this is the JAVA version of the workaround included in the referenced issue:
fab.show(new FloatingActionButton.OnVisibilityChangedListener() {
#Override
public void onShown(FloatingActionButton fab) {
try {
Field implField = FloatingActionButton.class.getDeclaredField("impl");
implField.setAccessible(true);
Object impl = implField.get(fab);
Class cls;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cls = impl.getClass().getSuperclass();
} else {
cls = impl.getClass();
}
Method mthd = cls.getDeclaredMethod("setImageMatrixScale", Float.TYPE);
mthd.setAccessible(true);
mthd.invoke(impl, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
I'm using the following:
GoogleApiClient mApiClient = new GoogleApiClient.Builder(this)
.addApi( Wearable.API )
...
Since Wearable.API is deprecated? What is the appropriate replacement?
I found something nice which is helpful
private class StartWearableActivityTask extends AsyncTask<Void, Void, Void> {
final String key;
public StartWearableActivityTask(String msg){
key = msg;
}
#Override
protected Void doInBackground(Void... args) {
Collection<String> nodes = getNodes();
for (String node : nodes) {
sendStartActivityMessage(node,key);
}
return null;
}
}
#WorkerThread
private Collection<String> getNodes() {
HashSet<String> results = new HashSet<>();
Task<List<Node>> nodeListTask =
Wearable.getNodeClient(getApplicationContext()).getConnectedNodes();
try {
// Block on a task and get the result synchronously (because this is on a background
// thread).
List<Node> nodes = Tasks.await(nodeListTask);
for (Node node : nodes) {
results.add(node.getId());
}
} catch (ExecutionException exception) {
Log.e(TAG, "Task failed: " + exception);
} catch (InterruptedException exception) {
Log.e(TAG, "Interrupt occurred: " + exception);
}
return results;
}
#WorkerThread
private void sendStartActivityMessage(String node,String event) {
Task<Integer> sendMessageTask =
Wearable.getMessageClient(this).sendMessage(node, event, new byte[0]);
try {
// Block on a task and get the result synchronously (because this is on a background
// thread).
Integer result = Tasks.await(sendMessageTask);
} catch (ExecutionException exception) {
Log.e(TAG, "Task failed: " + exception);
} catch (InterruptedException exception) {
Log.e(TAG, "Interrupt occurred: " + exception);
}
}
I found answer here:
https://developer.android.com/training/wearables/data-layer/migrate-to-googleapi
Migrate Wear apps to GoogleApi
Starting with version 11.8.0 of Google Play services, Wear OS apps should migrate away from the GoogleApiClient class and instead use client objects that are based on the GoogleApi class.
Use of GoogleApi makes it easier to set up asynchronous operations. For example, as described in the introduction to the Tasks API, you can obtain a Task object instead of a PendingResult object.
How can I get a list of videos available from a particular YouTube channel, using the API?
Basically every youtube channels has three section: Uploads, Playlist, Liked Videos. Had done some work with the playlist of a channels. Used youtube api version 3.Sharing my code:
First get the Playlists from a channel:
private void getPlayList() {
YouTube.Playlists.List playLists;
try {
playLists = youtube.playlists().list("id,status,snippet");//youtube is the Youtube object, already initialised
playLists.setChannelId(channelID);//channelID is the channel id which you want to fetch
playLists.setFields("items(id,status/privacyStatus,snippet(title,thumbnails/default/url))");
playLists.setMaxResults((long) 50);
AsynRequestClass asynRequestClass = new AsynRequestClass();
asynRequestClass.execute(playLists);
} catch (IOException e) {
e.printStackTrace();
Log.e(null, "Error occur " + e.toString());
}
}
private class AsynRequestClass extends AsyncTask<YouTube.Playlists.List, Void, PlaylistListResponse> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialogWithTitle("Loading PlayList");
}
#Override
protected PlaylistListResponse doInBackground(YouTube.Playlists.List... params) {
PlaylistListResponse playlistListResponse = null;
try {
Log.d(null, "PlayListList: " + params[0]);
playlistListResponse = params[0].execute();
Log.d(null,"PlayListResponse: "+playlistListResponse);
for (int i=0;i<playlistListResponse.getItems().size();i++){
//PlayListIdentifier,PlayListTitle,PlayListThumbnails are ArrayList<String>, already allocated and initialised
PlayListTitles.add(playlistListResponse.getItems().get(i).getSnippet().getTitle());
PlayListThumbnails.add(playlistListResponse.getItems().get(i).getSnippet().getThumbnails().getDefault().getUrl());
PlayListIdentifier.add(playlistListResponse.getItems().get(i).getId());
}
}catch (UserRecoverableAuthIOException e){
startActivityForResult(e.getIntent(),REQUEST_AUTHORIZATION);
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(PlaylistListResponse playlistListResponse){
super.onPostExecute(playlistListResponse);
hideProgressDialog();
PlayListDataAdapter.notifyDataSetChanged();//PlayListDataAdapter is the data adapter
}
}
Then get the playListItem or Videos:
private void loadPlayListItem(){
YouTube.PlaylistItems.List playListItemList = null;
try {
playListItemList =youtube.playlistItems().list("id,contentDetails,snippet,status");
playListItemList.setPlaylistId(playListID);
playListItemList.setFields("items(id,status/privacyStatus,snippet(title,thumbnails/default/url),contentDetails/regionRestriction)");
playListItemList.setMaxResults((long) 50);
AsyncRequestClass asyncRequestClass = new AsyncRequestClass();
asyncRequestClass.execute(playListItemList);
} catch (IOException e) {
e.printStackTrace();
}
}
//Class for asynchronous task
private class AsyncRequestClass extends AsyncTask<YouTube.PlaylistItems.List, Void, PlaylistItemListResponse> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialogWithTitle("Loading Video");
}
#Override
protected PlaylistItemListResponse doInBackground(YouTube.PlaylistItems.List... params) {
PlaylistItemListResponse playlistItemListResponse = null;
try {
Log.d(null, "PlayListListItem: " + params[0]);
playlistItemListResponse = params[0].execute();
Log.d(null,"PlayListItemListResponse: "+playlistItemListResponse);
int size = playlistItemListResponse.getItems().size();
for (int i=0;i<size;i++){
if (!playlistItemListResponse.getItems().get(i).getStatus().getPrivacyStatus().equals("private")){
//videoListIdentifier,videoListTitle,videoListThumbnails are ArrayList<String>, already allocated and initialised
videoTitles.add(playlistItemListResponse.getItems().get(i).getSnippet().getTitle());
videoThumbnails.add(playlistItemListResponse.getItems().get(i).getSnippet().getThumbnails().getDefault().getUrl());
videoIdentifier.add(playlistItemListResponse.getItems().get(i).getContentDetails().getVideoId());
}
}
}catch (UserRecoverableAuthIOException e){
startActivityForResult(e.getIntent(),REQUEST_AUTHORIZATION);
}catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(PlaylistItemListResponse playlistItemListResponse) {
super.onPostExecute(playlistItemListResponse);
hideProgressDialog();
videoListDataAdapter.notifyDataSetChanged();//videoListDataAdapter is the data adapter
}
}
Hadn't worked with the other two(Uploads,Liked videos), but think it can be possible in a similar manner.
I am a beginner in android programming.
I want to use the hidden method "getState()" of "com.android.internal.telephony.call" package to manage the state of an outgoing call such as activating, ringing, answering, rejecting and disconnecting.
But there is an error in the following code on the line indicated by "**".
Any help?
My code is :
import com.android.internal.telephony.*;
public class MainActivity extends Activity {
Class myclass;
ClassLoader cloader;
Method f;
Object o;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cloader = this.getClass().getClassLoader();
try {
myclass = cloader.loadClass("com.android.internal.telephony.Call");
// No error generated. "Call" class will be loaded.
}
catch (Exception e)
{
System.out.println(e.toString());
}
try {
f = myclass.getMethod("getState", null);
// No error generated.Method "f" will be assigned
} catch (Exception e) {
System.out.println(e.toString());
}
Constructor constructors[] = myclass.getDeclaredConstructors();
// There is one constructor only
Constructor constructor = null;
for (int i=0; i<constructors.length;i++)
{
constructor = constructors[i];
if (constructor.getGenericParameterTypes().length == 0)
break;
}
constructor.setAccessible(true);
try {
o = constructor.newInstance(null);
//*****an exception generated here.
//*****Exception is "java.lang.instantationexception"
}
catch (Exception e) {
System.out.println(e.toString());
}
try {
f = myclass.getMethod("getState", null);
// No error
} catch (Exception e) {
System.out.println(e.toString());
}
}
Don't try to call private members like this. It will not work across Android versions and even across manufacturer customized ROMs of the same version.
With API16 the new WAL (Write Ahead Logging) was introduced in Androids SQLiteDatabase class. I would like to test if WAL is enabled for a SQLite database. The app runs on older Android releases too, so I need a wrapper class for these new functions in SQLiteDatabase. The functions are:
public boolean isWriteAheadLoggingEnabled()
public boolean enableWriteAheadLogging()
public void disableWriteAheadLogging ()
In the Android Developer Blog I did find an article for a wrapper class that wraps new classes. What I didn't find is a wrapper for new methods in an already existing class. How should I do that?
The constructor for SQLiteDatabase is private so your're not going to be able to extend it and add "wrappers" to the class itself. You can however just write a "helper" wrapper like so:
public class WALWrapper {
private boolean mAvailable;
private Method mIsWriteAheadLoggingEnabled;
private Method mEnableWriteAheadLogging;
private Method mDisableWriteAheadLogging;
private final SQLiteDatabase mDb;
public WALWrapper(SQLiteDatabase db) {
mDb = db;
mAvailable = false;
try {
mIsWriteAheadLoggingEnabled =
SQLiteDatabase.class.getMethod("isWriteAheadLoggingEnabled");
mEnableWriteAheadLogging =
SQLiteDatabase.class.getMethod("enableWriteAheadLogging");
mDisableWriteAheadLogging =
SQLiteDatabase.class.getMethod("disableWriteAheadLogging");
mAvailable = true;
} catch (NoSuchMethodException e) {
}
}
/**
* Returns <code>true</code> if the {#link #isWriteAheadLoggingEnabled()},
* {#link #enableWriteAheadLogging()} and {#link #disableWriteAheadLogging()}
* are available.
* #return <code>true</code> if the WALWrapper is functional, <code>false</code>
* otherwise.
*/
public boolean isWALAvailable() {
return mAvailable;
}
public boolean isWriteAheadLoggingEnabled() {
boolean result = false;
if (mIsWriteAheadLoggingEnabled != null) {
try {
result = (Boolean) mIsWriteAheadLoggingEnabled.invoke(mDb);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return result;
}
public boolean enableWriteAheadLogging() {
boolean result = false;
if (mEnableWriteAheadLogging != null) {
try {
result = (Boolean) mEnableWriteAheadLogging.invoke(mDb);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
return result;
}
public void disableWriteAheadLogging() {
if (mDisableWriteAheadLogging != null) {
try {
mDisableWriteAheadLogging.invoke(mDb);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
}
}
}
}