Example usage for android.app.backup BackupManager BackupManager

List of usage examples for android.app.backup BackupManager BackupManager

Introduction

In this page you can find the example usage for android.app.backup BackupManager BackupManager.

Prototype

public BackupManager(Context context) 

Source Link

Document

Constructs a BackupManager object through which the application can communicate with the Android backup system.

Usage

From source file:com.andrada.sitracker.tasks.ImportAuthorsTask.java

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    if (intent == null) {
        return;/*from  ww w .j ava  2  s . co m*/
    }
    setupExtras(intent);

    this.importProgress = new ImportProgress(authorsList.size());

    //Filter out duplicates right away
    try {
        List<String> urlIds = helper.getAuthorDao().getAuthorsUrlIds();
        Map<String, String> prospectAuthorIds = new HashMap<String, String>();
        for (String auth : authorsList) {
            prospectAuthorIds.put(SamlibPageHelper.getUrlIdFromCompleteUrl(auth), auth);
        }
        for (String urlId : urlIds) {
            if (prospectAuthorIds.containsKey(urlId)) {
                authorsList.remove(prospectAuthorIds.get(urlId));
                this.importProgress.importFail(urlId);
            }
        }
        if (authorsList.size() == 0) {
            EventBus.getDefault().post(new ImportUpdates(this.importProgress));
        }
    } catch (SQLException e) {
        LOGW(TAG, "Failed to filter out duplicate authors", e);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(android.R.drawable.stat_notify_sync).setOngoing(true).setAutoCancel(false)
            .setContentTitle(getResources().getString(R.string.notification_import_title)).setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(this, ImportAuthorsActivity_.class);
    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(ImportAuthorsActivity_.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    for (String authUrl : authorsList) {
        try {
            if (shouldCancel) {
                //Make sure to cancel it here as well
                notificationManager.cancel(NOTIFICATION_ID);
                break;
            }
            SiteStrategy strategy = SiteDetector.chooseStrategy(authUrl, helper);
            if (strategy == null) {
                this.importProgress.importFail(authUrl);
            } else {
                int returnMsg = strategy.addAuthorForUrl(authUrl);
                if (returnMsg == -1) {
                    this.importProgress.importSuccess();
                } else {
                    this.importProgress.importFail(authUrl);
                }
            }

            if (shouldCancel) {
                //Make sure to cancel it here as well
                notificationManager.cancel(NOTIFICATION_ID);
                break;
            }
            EventBus.getDefault().post(new ImportUpdates(new ImportProgress(this.importProgress)));
            mBuilder.setContentText(getResources().getString(R.string.notification_import_progress,
                    importProgress.getTotalProcessed(), importProgress.getTotalAuthors())).setAutoCancel(false)
                    .setProgress(importProgress.getTotalAuthors(), importProgress.getTotalProcessed(), false);
            notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
            //Sleep for 5 seconds to avoid ban
            Thread.sleep(5000);

            if (!shouldCancel) {
                EventBus.getDefault().post(new ImportUpdates(this.importProgress));
            }
        } catch (InterruptedException e) {
            LOGW(TAG, "Importing was forcibly stopped", e);
        }
    }
    if (!shouldCancel) {
        Intent finishIntent = HomeActivity_.intent(this).authorsProcessed(importProgress.getTotalAuthors())
                .authorsSuccessfullyImported(importProgress.getSuccessfullyImported()).get();
        // The stack builder object will contain an artificial back stack for the
        // started Activity.
        // This ensures that navigating backward from the Activity leads out of
        // your application to the Home screen.
        stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent (but not the Intent itself)
        stackBuilder.addParentStack(HomeActivity_.class);
        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(finishIntent);

        BackupManager bm = new BackupManager(this);
        bm.dataChanged();

        AnalyticsHelper.getInstance().sendEvent(Constants.GA_ADMIN_CATEGORY, Constants.GA_EVENT_AUTHOR_IMPORT,
                Constants.GA_EVENT_IMPORT_COMPLETE, importProgress.getTotalAuthors());

        mBuilder.setProgress(0, 0, false).setOngoing(false).setAutoCancel(true)
                .setContentText(getResources().getString(R.string.notification_import_complete))
                .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
        notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
}

From source file:com.dwdesign.tweetings.app.TweetingsApplication.java

@Override
public void onSharedPreferenceChanged(final SharedPreferences preferences, final String key) {
    if (mServiceInterface != null
            && (PREFERENCE_KEY_AUTO_REFRESH.equals(key) || PREFERENCE_KEY_REFRESH_INTERVAL.equals(key))) {
        mServiceInterface.stopAutoRefresh();
        if (preferences.getBoolean(PREFERENCE_KEY_AUTO_REFRESH, false)) {
            mServiceInterface.startAutoRefresh();
        }/*from  w  w w  . j av  a  2 s  .co m*/
    } else if (PREFERENCE_KEY_ENABLE_PROXY.equals(key)) {
        reloadConnectivitySettings();
    }
    registerPush();
    if (backupManager == null) {
        backupManager = new BackupManager(this);
    }
    backupManager.dataChanged();
}

From source file:me.barrasso.android.volume.activities.ConfigurationActivity.java

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    LOGI(TAG, "onSharedPreferenceChanged(" + key + ')');
    Context context = getApplicationContext();
    if (null != context) {
        (new BackupManager(context)).dataChanged();
    }//from ww w  .j a v a 2 s . c o  m

    if (Constants.PREF_VOLUME_PANEL.equals(key)) {
        // TRACK: what theme is being used.
        String panel = sharedPreferences.getString(key, StatusBarVolumePanel.TAG);
        VolumeAccessibilityService.VolumePanelChangeEvent event = new VolumeAccessibilityService.VolumePanelChangeEvent(
                panel, Utils.supportsMediaPlayback(panel));
        onVolumePanelChangeEvent(event);
    } else if (Constants.PREF_REPORTING.equals(key)) {
        // TRACK: when the user opts out of being tracked.
    }
}

From source file:net.naonedbus.fragment.impl.FavorisFragment.java

@TargetApi(Build.VERSION_CODES.FROYO)
@Override//  ww w.  j a v a2  s .  c om
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (DBG)
        Log.d(LOG_TAG, "onCreate");

    setHasOptionsMenu(true);

    setEmptyMessageValues(R.string.error_title_empty_favori, R.string.error_summary_empty_favori,
            R.drawable.ic_star_empty);

    if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.ECLAIR_MR1)
        mBackupManager = new BackupManager(getActivity());

    mFavoriManager.addActionListener(mOnFavoriActionListener);
    // Initaliser le comparator avec la position actuelle.
    onLocationChanged(mLocationProvider.getLastLocation());

    // Gestion du tri par dfaut
    mStateHelper = new StateHelper(getActivity());
    mCurrentSort = mStateHelper.getSortType(this, SORT_NOM);

    initGroupes();
}

From source file:net.niyonkuru.koodroid.service.SessionService.java

private void login(String email, String password) throws IOException {
    try {/*  ww  w  . j a va 2s  . c om*/
        mPostRequest = new HttpPost(new URI(Config.LOGIN_URL));
    } catch (URISyntaxException e) {
        throw new ServiceException(e.getMessage());
    }

    List<NameValuePair> formData = buildFormData(email, password, getString(R.string.locale));
    try {
        /* fill the login request with form values */
        mPostRequest.setEntity(new UrlEncodedFormEntity(formData, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new ServiceException(e.getMessage());
    }

    Document doc;

    try {
        final HttpResponse response = mHttpClient.execute(mPostRequest);
        final Integer status = response.getStatusLine().getStatusCode();

        /* scumbag server did not return a 200 code */
        if (status != HttpStatus.SC_OK)
            throw new ServiceException(status.toString());

        HttpEntity entity = response.getEntity();

        doc = Jsoup.parse(EntityUtils.toString(response.getEntity()));

        if (entity != null) {
            entity.consumeContent();
        }
    } catch (UnknownHostException e) {
        throw new ServiceException(e.getMessage());
    } catch (ConnectTimeoutException e) {
        throw new ServiceException(getString(R.string.error_connection_timeout));
    } catch (ClientProtocolException e) {
        throw new ServiceException(e.getMessage());
    } catch (ParseException e) {
        throw new ServiceException(e.getMessage());
    } catch (SocketTimeoutException e) {
        throw new ServiceException(getString(R.string.error_response_timeout));
    } catch (IOException e) {
        // This could be caused by closing the httpclient connection manager
        throw new ServiceException(e.getMessage());
    }

    final Resources resources = getResources();
    final ContentResolver resolver = getContentResolver();

    /* this is a new user logging in */
    if (!email.equalsIgnoreCase(mSettings.email())) {
        /* clear old preferences */
        resolver.delete(Settings.CONTENT_URI, null, null);
    }

    try {
        new SubscribersHandler(resources, email).parseAndApply(doc, resolver);
        new LinksHandler(resources).parseAndApply(doc, resolver);

        ContentValues values = new ContentValues(3);
        values.put(Settings.EMAIL, email);
        values.put(Settings.PASSWORD, password);
        values.put(Settings.LAST_LOGIN, System.currentTimeMillis());

        resolver.insert(Settings.CONTENT_URI, values);

        new BackupManager(this).dataChanged();

    } catch (HandlerException e) {
        /* check if these errors could be caused by invalid pages */
        new ErrorHandler(resources).parseAndThrow(doc);
        throw e;
    }
}

From source file:com.andrada.sitracker.ui.fragment.AuthorsFragment.java

@Override
public boolean onActionItemClicked(@NotNull ActionMode mode, @NotNull MenuItem item) {
    mode.finish();/*from w  w  w .j ava  2 s .  c o m*/
    if (item.getItemId() == R.id.action_remove) {
        AnalyticsHelper.getInstance().sendEvent(Constants.GA_ADMIN_CATEGORY, Constants.GA_EVENT_AUTHOR_REMOVED,
                Constants.GA_EVENT_AUTHOR_REMOVED, (long) mSelectedAuthors.size());

        //This stuff is on background thread
        adapter.removeAuthors(mSelectedAuthors);
        return true;
    } else if (item.getItemId() == R.id.action_mark_read) {
        adapter.markAuthorsRead(mSelectedAuthors);
        AnalyticsHelper.getInstance().sendEvent(Constants.GA_ADMIN_CATEGORY,
                Constants.GA_EVENT_AUTHOR_MANUAL_READ, Constants.GA_EVENT_AUTHOR_MANUAL_READ,
                (long) mSelectedAuthors.size());

        BackupManager bm = new BackupManager(getActivity());
        bm.dataChanged();
        return true;
    } else if (item.getItemId() == R.id.action_open_authors_browser) {
        for (int i = 0; i < adapter.getCount(); i++) {
            if (mSelectedAuthors.contains(adapter.getItemId(i))) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(((Author) adapter.getItem(i)).getUrl()));
                getActivity().startActivity(intent);
            }
        }
        return true;
    }
    return false;
}

From source file:com.zns.comicdroid.activity.Comics.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.menu_edit:
        if (mViewType == VIEWTYPE_GROUP) {
            GroupDialogFragment dialogGroup = GroupDialogFragment.newInstance(mGroupId, mCurrentGroup.getName(),
                    mCurrentGroup.getTotalBookCount());
            dialogGroup.show(getSupportFragmentManager(), "GROUPDIALOG");
        } else {/*from w ww . ja  v a  2  s  .  c  o  m*/
            RenameDialogFragment dialogRename = new RenameDialogFragment();
            dialogRename.setName(mHeading);
            dialogRename.show(getSupportFragmentManager(), "RENAMEDIALOG");
        }
        return true;
    case R.id.menu_delete:
        new AlertDialog.Builder(this).setTitle(R.string.group_delete_title)
                .setMultiChoiceItems(new String[] { getString(R.string.group_delete_alt) }, null,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int pos, boolean checked) {
                                mDeleteComics = checked;
                            }
                        })
                .setPositiveButton(R.string.common_yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        getDBHelper().deleteGroup(mGroupId, mDeleteComics);
                        //Backup
                        BackupManager m = new BackupManager(Comics.this);
                        m.dataChanged();
                        //Back to start
                        Intent intent2 = new Intent(Comics.this, Start.class);
                        startActivity(intent2);
                        finish();
                    }
                }).setNegativeButton(R.string.common_no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                }).show();
        return true;
    case R.id.menu_editall:
        Intent intent = new Intent(this, Edit.class);
        int[] ids = mAdapter.getComicIds();
        intent.putExtra(Edit.INTENT_COMIC_IDS, ids);
        startActivity(intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.repay.android.adddebt.AddDebtActivity.java

public void requestBackup() {
    BackupManager bm = new BackupManager(this);
    bm.dataChanged();
}

From source file:com.google.android.apps.dashclock.ExtensionManager.java

/**
 * Replaces the set of active extensions with the given list.
 *//*from w  ww  .  j ava 2 s . c om*/
public void setInternalActiveExtensions(List<ComponentName> extensions) {
    StringBuilder sb = new StringBuilder();

    for (ComponentName extension : extensions) {
        if (sb.length() > 0) {
            sb.append(",");
        }
        sb.append(extension.flattenToString());
    }

    mDefaultPreferences.edit().putString(PREF_ACTIVE_EXTENSIONS, sb.toString()).apply();
    new BackupManager(mApplicationContext).dataChanged();

    mInternalActiveExtensions.clear();
    mInternalActiveExtensions.addAll(extensions);
    setActiveExtensions(getActiveExtensionNames());
}