package com.example.broadcast;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.format.Formatter;
import android.widget.TextView;
import android.widget.Toast;

public class MemoryAvailableActivity extends Activity {
    private BroadcastReceiver timeReceiver = new TimeReceiver();
    private IntentFilter filter = new IntentFilter(
            Intent.ACTION_TIME_TICK);
    private TextView memAvailable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.memory_available);

        memAvailable = (TextView) findViewById(R.id.memAvailable);
        updateMemoryAvailable();
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(timeReceiver, filter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(timeReceiver);
    }

    private void updateMemoryAvailable() {
        ActivityManager mgr =
                (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        MemoryInfo mi = new MemoryInfo();
        mgr.getMemoryInfo(mi);

        String memAvailAmount =
                Formatter.formatFileSize(getApplicationContext(),
                        mi.availMem);
        
        String memAvailPrefix = getString(R.string.memoryAvailable);
        
        memAvailable.setText(memAvailPrefix + memAvailAmount
                + "\n" + memAvailable.getText());

        Toast.makeText(MemoryAvailableActivity.this,
                memAvailPrefix + mi.availMem,
                Toast.LENGTH_SHORT).show();
    }

    // Once a minute update the memory available
    class TimeReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
                updateMemoryAvailable();
            }
        }
    }
}
