AdvertisingIdClient getAdvertisingIdInfo hangs forever - android

I'm trying to get advertising ID from Google Play services API. Here is a sample code:
...
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
...
public class MyActivity extends Activity {
#Override
protected void onStart() {
super.onStart();
Thread thr = new Thread(new Runnable() {
#Override
public void run() {
try {
Context ctx = MyActivity.this.getApplicationContext();
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(ctx);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
});
thr.start();
synchronized (thr) {
try {
thr.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
When I'm calling getAdvertisingIdInfo method, application hangs forever (no matter with debugger or not).
I'm using Windows ADT 22.3, Android SDK API 19, Google Play SDK rev. 16, Android 4.4.2 Nexus devices. I'm integrating API as described here: https://developer.android.com/google/play-services/id.html
What could be a reason?

I found the reason. It shouldn't block onStart() handler because blocked context blocks Play API in ID settings obtaining. Fixed code looks like this:
#Override
protected void onStart() {
super.onStart();
Thread thr = new Thread(new Runnable() {
#Override
public void run() {
try {
Context ctx = MyActivity.this.getApplicationContext();
AdvertisingIdClient.Info adInfo = AdvertisingIdClient.getAdvertisingIdInfo(ctx);
finished(adInfo);
} catch (...) {
// All exceptions blocks
}
finished(null);
}
});
thr.start();
}
private void finished(final AdvertisingIdClient.Info adInfo){
if(adInfo!=null){
// In case you need to use adInfo in UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
// Do some stuff with adInfo
}
});
}
}
It would be helpful if official instructions had such usage comments.

Unfortunately the getAdvertisingIdInfo call needs to be done from a background thread, you should not block the main thread while invoking it. Seems like there is no option to get the AdId synchronously.
---- EDIT----
I could achieve this by running on a new thread. Here is what finally work for me. It is not hanging anymore (May not be an ideal)
getGAIDSync(){
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable() {
#Override
public void run() {
getGoogleAdsIDAsyncTask.execute().get(5000, TimeUnit.MilliSecond);
latch.countDown();
}}).start();
try {
latch.await(5000,TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Related

ProgressDialog does not work even using thread

I am new in Android development. I am trying to show a ProgressDialog. I see lots of tutorial that say for showing dialog must use thread. As you can see snippet code is using thread.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
refreshFromFeed();
} catch (InterruptedException e) {
e.printStackTrace();
}
setContentView(R.layout.activity_main);
}
private void refreshFromFeed() throws InterruptedException {
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis()/1000));
}
};
th.start();
dialog.dismiss();
}
protected void onRefresh(View view) throws InterruptedException {
refreshFromFeed();
}
The log shows it took 5 second, however, I cannot see any dialog on my screen and I can do anything on the screen. Even I use on a physical device. I've used debugging mode. There is no exception.
onRefresh is an event by onClick that declared on it's xml.
I've made a little bit changes of your code read it carefully.
private void refreshFromFeed() throws InterruptedException {
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
dialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo",String.valueOf(System.currentTimeMillis()/1000));
}
};
th.start();
}
private void refreshFromFeed() throws InterruptedException {
final ProgressDialog dialog = ProgressDialog.show(getActivity(),"Loading","Wake up after some sleep");
Thread th = new Thread() {
public void run() {
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis() / 1000));
try {
Thread.sleep(5000);
dialog.dismiss(); // dismiss your dialog here
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis() / 1000));
}
};
th.start();
}
You still run the ProgressDialog in your UI thread.
ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
New thread created after this line, not before this line!
You are dismissing your dialog just right after showing it.
Maybe you want to move your "dialog.dismiss();" to inside the thread. Remember that you need to dismiss the dialog on UI Thread, otherwise it will crash your app:
private void refreshFromFeed() throws InterruptedException {
final ProgressDialog dialog = ProgressDialog.show(this,"Loading","Wake up after some sleep");
Thread th = new Thread(){
public void run(){
Log.d("TimeFrom", String.valueOf(System.currentTimeMillis()/1000));
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("TimeTo", String.valueOf(System.currentTimeMillis()/1000));
runOnUiThread(new Runnable() {
#Override
public void run() {
dialog.dismiss();
}
});
}
};
th.start();
}
I see lots of tutorial that say for showing dialog must use thread.
You don't explicitly need a thread to show a ProgressDialog, this is just an example to dismiss it after 5000 ms

Unable to update seekbar with Handler

I am trying to update seekbar with respect to the progress of the song in MediaPlayer.
I am using Thread to do that task.
First i have used Thred inside thread and trying to update the UI but it crashing the app and says that only original thread can attached to the view.
Then i have try to update it with handler inside the thread runnable. which works fine but it is not updating the seekbar. When i have do log then i come to know loop is not going inside my handler. I dont know where is the problem. Please help me to updating SeekBar.
Code:
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
try {
if ((musicPath != mIRemoteService.getPath())) {
System.out.println("..... MUSIC CHANGE.....");
setOrUpdateData();
updateFragmentLayout();
}
// Displaying Current Duration time/Progress
new Handler().post(new Runnable() {
#Override
public void run() {
try {
songCurrentDurationLabel.setText(""+ Utilities.milliSecondsToTimer(mIRemoteService.position()));
songProgressBar.setProgress((int)mIRemoteService.position());
System.out.println("Runnnnn.........");
//songProgressBar.invalidate();
} catch (RemoteException e) {
e.printStackTrace();
System.out.println("Runnnnn......... EXCEPTION....");
}
}
});
System.out.println("Runnnnn.........MAIN....");
if (!(mIRemoteService.isPlayerRunning())) {
btnPlay.setImageDrawable(getResources().getDrawable(R.drawable.play_now_playing));
mHandler.removeCallbacks(mUpdateTimeTask);
System.out.println("Runnnnn.........MAIN....IF");
}else{
System.out.println("Runnnnn.........MAIN....ELSE");
mHandler.post(mUpdateTimeTask);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
you can use either a handler or a thread, with thread you should make sure to post the modifications on the UI thread:
private class UpdateSeekBar extends Thread
{
#Override
public void run()
{
super.run();
while (null != mp && mp.isPlaying() && this.isAlive())
{
//final int min = (mp.getCurrentPosition() / 1000) / 60;
//final int sec = (mp.getCurrentPosition() / 1000) % 60;
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
try
{
songCurrentDurationLabel.setText("" + Utilities.milliSecondsToTimer(mIRemoteService.position()));
songProgressBar.setProgress((int) mIRemoteService.position());
System.out.println("Runnnnn.........");
// songProgressBar.invalidate();
}
catch (RemoteException e)
{
e.printStackTrace();
System.out.println("Runnnnn......... EXCEPTION....");
}
}
});
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}

http connection from MainActivity

I have a little problem. In my android app, i have to connect to an online server.
The connection should be called with an click-button an as an backround service. I know that I must put the network connection in a thread, but i don't know how it works.
I put the call in a own method wich creates a thread but at compilation i got a error message.
here is my code:
Button:
ImageView refresher = (ImageView)findViewById(R.id.imgRefresh);
refresher.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
httpThread();
}
});
thread method:
private void httpThread(){
final Handler h = new Handler();
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
h.post(new Runnable(){
#Override
public void run() {
try{
vomServerholenUndSpeichern();
FileInputStream inStream = null;
try {
inStream = openFileInput("test.xml");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
leseDatei(inStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
createListView("test.xml");
System.out.println(inStream);
drawListView();
} catch (Exception e){
e.printStackTrace();
}
}
});
}
});
thread.start();
}
Can someone help me to fix the problem?
You have to use AsyncTask, is not difficult.
AsyncTask are necessary to avoid block UI during your connection operation, the method doInbackGround of AsyncTask is used for this kind of operations (it runs in a thread different from the UI), while int the onPostExecute (this run on the UI) of the task you will manage your httpResult;)

unable to see toast inside oncreate

import android.widget.Toast;
public class Security extends MainActivity {
Socket sock,sock1;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.security);
new Thread(new Runnable()
{
public void run()
{
try{
sock=new Socket(ip,port1);
BufferedReader br=new BufferedReader(new InputStreamReader(sock.getInputStream()));
String a=br.readLine();
Thread.sleep(2500);
Toast.makeText(getApplicationContext(),"Please Enter the result of operation for no "+a,Toast.LENGTH_LONG).show();
}
catch(UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}).start();
}
}
Not able to view toast when Security started. I dont know why? it is like that it should be wit in oncliklistener.?
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),"Please Enter the result of operation for no "+a,Toast.LENGTH_LONG).show();
}
});
You can only show toasts in the main UI thread.
If you need to do things on the UI thread from a background thread, have a look at runOnUiThread().

Show Toast from a thread started in a broadcast receiver

I have a BroadcastReceiver.
There I create a new Thread.
How can I show a toast in that thread?
Thanks
Use below code for perform UI operation from non-UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Try This code
public void start_insert() {
pDialog.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
// Do Something in Background
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
handler22.sendMessage(handler22.obtainMessage(what));
}
}.start();
}
private Handler handler22 = new Handler() {
#Override
public void handleMessage(Message msg) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "SuccessFull",
10).show();
}
};
Activity_Name.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Use this code to update UI thread or execute any UI related operation.

Categories

Resources