Data Backup into Google Servers using Android Backup Service in Android - android

Im trying to do the backing up of my application's data into the Google Servers..
For doing this I've implemented a BackupAgent in my code and I included this in the Android Manifest file and "Meta-data" ( Got after registered my Application's package with the Android Backup Service)
When I run the application to do the backup this is not performing the backup.. Im using Nexus one device (connected to WIFI also) .
Could any one please let me know why it is not calling my BackupAgent's onBackup() method?
Am I missing some thing, to include in the Android manifest file or some where in the program?
The below is my manifest file..
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.simpledatabackup"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name"
android:backupAgent="MyBackupAgent"
android:debuggable="true">
<activity android:name=".SimpleDatabackup"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.backup.api_key"
android:value="AEdPqrEAAAAIZn2ysSLR5wNbcq1uaoWQO0HuipMetQENVTsilw" />
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
and the source file is
public class SimpleDatabackup extends Activity {
private SharedPreferences myPrefs ; // Shared Preferences
BackupManager mBackupManager;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPrefs = this.getSharedPreferences("shared_prefs", MODE_WORLD_READABLE);
SharedPreferences.Editor edit = myPrefs.edit();
edit.putString("firstname", "uday") ;
edit.putString("lastname", "kiran") ;
edit.commit() ;
mBackupManager.dataChanged();
}
}
My Backup Agent is some thing like this: I have not implemented the functionality inside is onBackup() and onRestore(). Once if it is called i will implement what ever i want..
public class MyBackupAgent extends BackupAgent {
#Override
public void onCreate() {
System.out.println("In MyBackuAgent's onCreate() method");
}
#Override
public void onBackup(ParcelFileDescriptor arg0, BackupDataOutput arg1,
ParcelFileDescriptor arg2) throws IOException {
System.out.println("In MyBackuAgent's onBackup()");
// TODO Auto-generated method stub
}
#Override
public void onRestore(BackupDataInput data, int appVersionCode,
ParcelFileDescriptor newState) throws IOException {
}
}

In the application tag in the manifest include
android:allowBackup="true"
android:restoreAnyVersion="true"
android:backupAgent="<package>.MyBackupAgent"
Please follow the "Testing your BackupAgent" section to invoke the backup instantly for testing.
BackupManagerService schedules the backup regularly in hour interval after the datachanged call to backupmanager. [grepcode]

Related

In Android manifest android:name shows me error -- parse sdk android

Below is the code code of Android manifest
<application
android:name="com.example.m1.parsedemo.MainActivity" // this line show error
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
and the main activity java file is
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.enableLocalDatastore(this);
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("31e1ed2c6158fa0d01c3a5201a15e4af3f228a5b")
// if define
.clientKey("7d930e5059ba7ca44ce7083a6708b99eb70d9b4b")
.server("http://35.154.249.137:80/parse/")
.build()
);
ParseUser.enableRevocableSessionInBackground();
ParseObject gameScore = new ParseObject("Manish");
gameScore.put("score", 1337);
gameScore.put("playerName", "Manish");
gameScore.put("cheatMode", false);
gameScore.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e == null) {
Log.i("sucess","sucess");
} else {
Log.i("error",e.toString());
}
}
});
}
I am following this guideline -> parse
Removing
android:name=""
shows no error, but cant connect to the server and adding it, show error. I am stuck here cant connect to parse server.
And also please tell me is there any wrong code in main activity java file.
Thanx
You won't need this or you're referencing the wrong file in here:
android:name="com.example.m1.parsedemo.MainActivity" // this line show error
Which you already have:
<activity android:name=".MainActivity"
If you're trying to reference the Application class of your project, use a different name and create another class like calling it App, then:
android:name=".App"
In your AndroidManifest.xml application tag and these codes inside the onCreate() of the App class:
import com.parse.Parse;
import android.app.Application;
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("31e1ed2c6158fa0d01c3a5201a15e4af3f228a5b")
// if define
.clientKey("7d930e5059ba7ca44ce7083a6708b99eb70d9b4b")
.server("http://35.154.249.137:80/parse/")
.build()
);
}
}
Just like the documentation.
This should be name of your application class, not the activity class
<application
android:name="com.example.m1.parsedemo.MainActivity" // this line show error
</application
correct it with the application class which looks like this
public class App extends Application {
#Override
public void onCreate() {
super.onCreate();
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("YOUR_APP_ID")
// if defined
.clientKey("YOUR_CLIENT_KEY")
.server("http://localhost:1337/parse/")
.build()
);
}
}

BackUpAgentHelperClass is not getting called

I want to backup data in Android using MyBackUpAgent class which extends BackupAgentHelper. I am using SharedPreferences in order to store data.
My mainactivity code is:
public class MainActivity extends Activity {
EditText inputtext;
TextView outputtext;
Button submit;
public static SharedPreferences sharedprefs;
static final String File_Name_Of_Prefrences ="godplay_preferences";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
init();
sharedprefs=getSharedPreferences(File_Name_Of_Prefrences,MODE_PRIVATE);
System.out.println("value="+sharedprefs.getString("Input",""));
outputtext.setText(sharedprefs.getString("Input",""));
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
populateUI();
}
});
}
public void populateUI()
{
String savedinput=inputtext.getText().toString();
System.out.println("savedinput="+savedinput);
outputtext.setText(savedinput);
sharedprefs=getSharedPreferences(File_Name_Of_Prefrences,MODE_PRIVATE);
Editor editor=sharedprefs.edit();
editor.putString("Input",inputtext.getText().toString());
editor.commit();
requestBackup();
}
private void init() throws ClassCastException
{
inputtext=(EditText) findViewById(R.id.edtInputText);
outputtext=(TextView) findViewById(R.id.txtOutputText);
submit=(Button) findViewById(R.id.btnSubmit);
}
public void requestBackup() {
BackupManager bm = new BackupManager(getApplicationContext());
bm.dataChanged();
}
}
My MyBackUpAgent class:
public class MyBackUpAgent extends BackupAgentHelper{
static final String PREFS_BACKUP_KEY = "backup";
String key_string="Hello World";
#Override
public void onCreate() {
System.out.println("********************");
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this,MainActivity.File_Name_Of_Prefrences);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
My mainfest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.godplay"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:restoreAnyVersion="false"
android:backupAgent=".MyBackUpAgent"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.godplay.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIhjloadYCTPUNo3yPsSX6LKmziiumZiQVlEEdBA" />
</application>
</manifest>
So far I have tried with bmgr tool to test, it is executing successfully with bmgr tool. However, on testing on Android device and emulator, back up is not happening, nor restoring.
Also, I have tested this on Android 5.1, Android 4.2, and Android 4.0 but still no luck.
It seems to me that my MyBackUpAgent class is never getting called, and I have tried breakpoints in MyBackUpAgent Class and validated it. Its never get hit.
What am I doing wrong?
Docs mention Conditions For Backup Schedule:
The user has enabled backup on the device in Settings > Backup & Reset.
At least 24 hours have elapsed since the last backup.
The device is idle and charging.
The device is connected to a Wi-Fi network. If the device is never connected to a wifi network, then Auto Backup never occurs.
If backup is working for you with bmgr tool but not on a real device / emulator, it's possible you are not meeting all those conditions, therefore backup never occur.
In your AndroidManifest.xml file, try changing
android:backupAgent=".MyBackUpAgent"
with the fully qualified class name, i.e.
android:backupAgent="com.abh.utils.MyBackUpAgent"
but of course changing "com.abh.utils" with the name of the package MyBackUpAgent.java is in.
I had a similar problem and have searched everywhere with no luck. Finally found the solution.
It seems that the BackupAgent needs to be in the top package with no preceding dot. So try changing:
android:backupAgent=".MyBackUpAgent"
to
android:backupAgent="MyBackUpAgent"
You can refer to developer document,
https://developer.android.com/guide/topics/data/backup.html#PerformingBackup
A backup request does not result in an immediate call to your onBackup() method. Instead, the Backup Manager waits for an appropriate time
you can use "bmgr tool" to initiate immediate backup whiling developing your app.
Make sure you call
adb shell bmgr run
to simulate the backup.
Also try using local transport to backup at any time:
adb shell bmgr transport android/com.android.internal.backup.LocalTransport

SharedPreferencesBackupHelper auto restore doesn't work

I'm trying to use SharedPreferencesBackupHelper to save my SharedPreferences value to cloud.
AndroidManifest.xml
<application
android:allowBackup="true"
android:backupAgent=".DataBackupAgent"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.backup.api_key" android:value="AEdPqrEAAAAIXMH86OqosQlXYuS0QbfyOaZT8fUadY1QUDzo2w" />
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
DataBackupAgent.java:
public class DataBackupAgent extends BackupAgentHelper {
public static final String PREFS = "data_prefs";
public static final String PREFS_BACKUP_KEY = "myprefs";
#Override
public void onCreate() {
SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS);
addHelper(PREFS_BACKUP_KEY, helper);
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
backupManager = new BackupManager(this);
prefs = getSharedPreferences(DataBackupAgent.PREFS, Context.MODE_PRIVATE);
edit = prefs.edit();
text = (EditText)findViewById(R.id.editText);
String value = prefs.getString(DataBackupAgent.PREFS_BACKUP_KEY,"");
text.setText(value);
Button btnBackup = (Button)findViewById(R.id.button);
btnBackup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit.putString(DataBackupAgent.PREFS_BACKUP_KEY,text.getText().toString());
edit.commit();
backupManager.dataChanged();
}
});
}
My steps:
Write something at the EditText, click Backup button
Close app and open again. The saved value will be shown in EditText
Uninstall the app and reinstall again. The saved value is not shown in EditText at all.
Edit at 27/02/2015:
I added the following code to restore manually:
backupManager.requestRestore(new RestoreObserver() {
#Override
public void restoreFinished(int error) {
super.restoreFinished(error);
String value = prefs.getString(DataBackupAgent.PREFS_BACKUP_KEY,"");
text.setText(value);
}
#Override
public void restoreStarting(int numPackages) {
super.restoreStarting(numPackages);
}
#Override
public void onUpdate(int nowBeingRestored, String currentPackage) {
super.onUpdate(nowBeingRestored, currentPackage);
}
});
Unfortunately no callback functions are called.
This means back or auto restore doesn't work at all. Any idea? Thanks
My steps:
1. Write something at the EditText, click Backup button
2. Close app and open again. The saved value will be shown in EditText
3. Uninstall the app and reinstall again. The saved value is not shown in EditText at all.
To test your implementation there are others steps related to the use of bmgras we can see here.
Nevertheless I implemented this feature some days ago and following the steps in the documentation using a real device - Samsung SII - the automatic restore doesn't happen BUT using the emulator all was fine.
Logcat will show you all the operation output details.
IMO, the Android Data Backup feature is not reliable today. We can see some discussion about the implementation problems here and here.
Hope it helps!

Android starts correct activity from Eclipse - but not from the phone

When I launch my app from Eclipse to my phone, it launches the Launcher first and then my main activity. It successfully passes a variable to the main activity. I check that the username has been logged with a toast.
When I launch my app from my phone directly, it goes straight to the main activity; the main activity registers the variable as null.
I created a test app that performs EXACTLY the same function as the launcher in this one; their manifests are identical except for the activity names; and that test app functions correclty from the phone and when I install it from Eclipse.
this is a real brain-teaser.
Here is the code for the starter activity:
public class SecureAppStarter extends Activity {
TextView report;
WebView input;
Context thisContext = this;
String thisValue, url;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.starter);
initialize();
WebViewClient rclient = new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
return false;
}
#Override
public void onLoadResource(WebView view, String url){
input.getSettings().setJavaScriptEnabled(true);
input.addJavascriptInterface(new CustomJavaScriptInterface(thisContext), "Android");
}
#Override
public void onPageFinished(WebView view, String url){
report.setText(""+thisValue);
if (thisValue!= null){
Intent passOn = new Intent("arbuckle.app.MainActivity");
passOn.putExtra("username", thisValue);
startActivity(passOn);
}
}
};
rclient.onPageFinished(input, url);
input.setWebViewClient(rclient);
input.loadUrl(url);
}
public class CustomJavaScriptInterface {
Context mContext;
CustomJavaScriptInterface(Context context) {
mContext = context;
}
public void getValue(String value){
thisValue = value;
}
}
private void initialize() {
report = (TextView) findViewById(R.id.tvViewName);
input = (WebView) findViewById(R.id.wbWebAuth);
url = "http://URL.of.data.com";
}
}
And here is the manifest:
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="SecureAppStarter"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ArbuckleAppActivity"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation">
<intent-filter>
<action android:name="arbuckle.app.ArbuckleAppActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Well I figured it out.
I have been installing/uninstalling versions of the app for weeks where the main activity was the launcher. clearly that gets kept somewhere in Android cache and it was choosing the main activity to launch even though it wasn't the launcher anymore.
So I uninstalled the app completely; and reinstalled. Now it works.
Does anyone think I hacked at the problem instead of solving it? Should I expect further problems down the road?

BackupAgentHelper never called in Android 2.2

I'm trying to implement Data Backup into my application. I build Android 2.2 project, and run in Galaxy s2 4.0.3.
I try to use: BackupManagerTest to save preferences to the cloud
This is my code :
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.amdroid.backuptest"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<application
android:allowBackup="true"
android:backupAgent="net.amdroid.backuptest.MyBackupAgent"
android:icon="#drawable/icon"
android:label="#string/app_name" >
<activity
android:name=".BackupManagerTestActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.backup.api_key"
android:value="AEdPqrEAAAAI7_yf1xqlpltWZPZiKMHVlDgn3nMfgotjUweSUg" />
</application>
</manifest>
MyBackupAgent.java
public class MyBackupAgent extends BackupAgentHelper {
// The names of the SharedPreferences groups that the application maintains. These
// are the same strings that are passed to getSharedPreferences(String, int).
static final String PREFS_TEST = "testprefs";
// An arbitrary string used within the BackupAgentHelper implementation to
// identify the SharedPreferenceBackupHelper's data.
static final String MY_PREFS_BACKUP_KEY = "myprefs";
// Simply allocate a helper and install it
#Override
public void onCreate() {
SharedPreferencesBackupHelper helper =
new SharedPreferencesBackupHelper(this, PREFS_TEST);
addHelper(MY_PREFS_BACKUP_KEY, helper);
Log.d("Test", "Adding backupagent...");
}
}
My Activity
public class BackupManagerTestActivity extends Activity {
private SharedPreferences prefs;
private Editor edit;
private BackupManager backupManager;
private EditText text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
backupManager = new BackupManager(getBaseContext());
prefs = getSharedPreferences(MyBackupAgent.PREFS_TEST, Context.MODE_PRIVATE);
edit = prefs.edit();
text = (EditText) findViewById(R.id.editName);
String nome = prefs.getString("KEY_NAME", "");
text.setText(nome);
Button button = (Button) findViewById(R.id.buttonSave);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
edit.putString("KEY_NAME", text.getText().toString());
edit.commit();
Log.d("Test", "Calling backup...");
backupManager.dataChanged();
}
});
}
}
So MyBackupAgent never called. I don't know the reason.
When you call backupManager.dataChanged(), it merely schedules your app for backup. It does not mean your backup helper is called right away.
From http://developer.android.com/guide/topics/data/backup.html:
You can request a backup operation at any time by calling dataChanged(). This method notifies the Backup Manager that you'd like to backup your data using your backup agent. The Backup Manager then calls your backup agent's onBackup() method at an opportune time in the future. Typically, you should request a backup each time your data changes (such as when the user changes an application preference that you'd like to back up). If you call dataChanged() several times consecutively, before the Backup Manager requests a backup from your agent, your agent still receives just one call to onBackup().
Note: While developing your application, you can request a backup and initiate an immediate backup operation with the bmgr tool.
Instructions for the bmgr tool can be found at:
http://developer.android.com/tools/help/bmgr.html
To force all pending backup operations to run immediately, use:
adb shell bmgr run

Categories

Resources