2015-12-01 135 views
1

我試圖在Android 6及更低版本中使用Android自動備份功能,但在重新安裝我的應用程序後,將不會恢復任何內容。使用Android自動備份備份應用程序文件

清單:

<application 
      android:allowBackup="true" 
      android:backupAgent=".BackupAgent" 
      android:fullBackupOnly="true" 
      android:fullBackupContent="true" 
      android:name="com.App"> 

      <meta-data 
       android:name="com.google.android.backup.api_key" 
       android:value="API_KEY"/> 
</application> 

BackupAgent:

public class BackupAgent extends BackupAgentHelper { 
    @Override 
    public void onCreate() { 
     super.onCreate(); 
     BackupHelper helper = new FileBackupHelper(getApplicationContext(), Realm.getDefaultInstance().getPath()); 

     addHelper("database", helper); 
    } 
} 

片段,其使用領域:

public class NewBlockNumber extends Fragment implements Validator.ValidationListener { 
    private Realm mRealm; 
    private RealmChangeListener mRealmChangeListener = new RealmChangeListener() { 
     @Override 
     public void onChange() { 
      BackupManager bm = new BackupManager(getContext()); 
      bm.dataChanged(); 
     } 
    }; 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     mRealm = Realm.getDefaultInstance(); 
     mRealm.addChangeListener(mRealmChangeListener); 

     return null; 
    } 
} 
+0

根據此文檔http://developer.android.com/guide/topics/data/backup.html,您需要覆蓋'onBackup'和'onRestore'。 – beeender

+0

@beeender我擴展了'BackupAgentHelper',因此不需要實現這些方法。 – Alireza

+0

'new FileBackupHelper(getApplicationContext(),Realm.getDefaultInstance()。getPath());'我懷疑你可能需要傳遞文件名而不是整個路徑。 – beeender

回答

0

你有使用db的文件名實例化FileBackupHelper,而不是路徑。絕對路徑然後由BackupAgent解決。你可以調試它並跟蹤所有的步驟來檢查。 我有這個代碼運行在我的應用程序,它完美的作品。

@Override 
public void onCreate() { 
    FileBackupHelper hosts = new FileBackupHelper(this, Realm.getDefaultInstance().getConfiguration().getRealmFileName()); 
    addHelper(Realm.getDefaultInstance().getConfiguration().getRealmFileName(), hosts); 
} 

@Override 
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data, 
        ParcelFileDescriptor newState) throws IOException { 
    Log.w("Backup", "onBackup"); 
    // Hold the lock while the FileBackupHelper performs backup 
    synchronized (MainActivity.sDataLock) { 
     Log.w("Backup", "backing up..."); 
     super.onBackup(oldState, data, newState); 
    } 
} 

@Override 
public void onRestore(BackupDataInput data, int appVersionCode, 
         ParcelFileDescriptor newState) throws IOException { 
    Log.w("Backup", "onRestore"); 
    // Hold the lock while the FileBackupHelper restores the file 
    synchronized (MainActivity.sDataLock) { 
     Log.w("Backup", "Restoring data..."); 
     super.onRestore(data, appVersionCode, newState); 
    } 
}