How to show sync failed message

2019-01-26 20:46发布

问题:

I've build a contacts sync adapter. It's all working fine but I need one more thing. If for some reason the sync does not complete successfully, I want to show a message like Google account is showing when the sync fails

回答1:

The solution was to set the delay on the sync result. After this delay the sync will be restarted.

try {
    DO THE SYNCHRONIZATION
} catch (AuthenticationException e) {
    Log.e(TAG, "AuthenticationException");
    syncResult.stats.numAuthExceptions++;
    syncResult.delayUntil = 180;
} catch (ParseException e) {
    Log.e(TAG, "ParseException");
    syncResult.stats.numParseExceptions++;
} catch (IOException e) {
    Log.e(TAG, "IOException");
    syncResult.stats.numIoExceptions++;
    syncResult.delayUntil = 180;
}


回答2:

I think what you want are Toasts

Simple Toast:

Toast.makeText(context, text, duration).show();

text is, as you can imagine, the text you want to be displayed. duration is either Toast.LENGTH_SHORT or Toast.LENGTH_LONG (depends in how long the Toast sahll be visible)

More complicated approach with picture in the toast: (sync_toast_lo.xml)

<?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/SynctoastLayout"
    android:background="@android:color/black">

  <ImageView
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:src="@drawable/your_logo"
    android:layout_toLeftOf="@+id/textView"
    android:layout_margin="5dip"
    android:id="@+id/syncLogo">
  </ImageView>

  <TextView
    android:id="@+id/syncFailedText"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:text="The sync has failed!"
    android:gravity="center"
    android:textColor="@android:color/white">
  </TextView>
</RelativeLayout>

And in your code:

LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.Sync_toast_lo,
                               (ViewGroup) findViewById(R.id.SynctoastLayout));

Toast toast = new Toast(this);
toast.setView(view);
toast.show();