Search code examples
javaandroidbroadcastreceiver

ANDROID: Send data to Parse SDK database after user quits from application


I want to send data to parse SDK when the user quits my application.
I am able to send data through parse SDK but i want it to send just after user quits from my application.
Right now, my code looks like below:

Main Activity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.create_todo);
        setTitle(R.string.create_todo);
        alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, AlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

        alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                AlarmManager.INTERVAL_FIFTEEN_MINUTES,
                AlarmManager.INTERVAL_FIFTEEN_MINUTES, alarmIntent);
}

AlarmReceiver.java

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        MyAsyncTask asyncTask = new MyAsyncTask();
        asyncTask.execute(new String[]{});
    }


    class MyAsyncTask extends AsyncTask<String,Void,String>
    {

        @Override
        protected String doInBackground(String... params) {
            try {
                ParseObject parseObject = new ParseObject("Todo");
                parseObject.put("name", "abc");
                parseObject.save();
            }
            catch(ParseException e)
            {
            }
            return null;
        }
    }
}

I have registered receiver in android.manifest file like this:

<receiver android:name=".utilities.AlarmBroadcastReciver">

            <intent-filter>
                <action android:name="Intent">
                </action>
            </intent-filter>

        </receiver>

Solution

  • Is this the only one Activity in the app?

    There is a possiblity that you would override the Activity onStop() method. It is called every time an Activity is somehow hidden - there's a new activity, the user went back to the "desktop", etc. You could send data in this method.

    @Override
    protected void onStop() {
        super.onStop();
    
        Log.d(TAG, "ON STOP");
    }
    

    I am not sure if you should call the sending method before or after super.onStop(), just try it.