Wednesday, August 15, 2012

Android-Activity

Android Activity
An activity having UserInterface its sub class of Activity
An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View). While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup). There are two methods almost all subclasses of Activity will implement:
  a) Backup Activity
  b) Notification Activity
  c) setContentView from XML for activity
  d) more than one Activity
  e) find user control by using findbyview
  f) A simple form
  g) Link from with POJO
  h) LifeCycle
   a) Backup Activity
This class  using for take backup your database or your application any other data.
class BackAsyncTask extends AsyncTask<String,Void,Integer> {
    public interface CompletionListener {
        void onBackupComplete();
        void onRestoreComplete();
        void onError(int errorCode);
    }
    public static final int BACKUP_SUCCESS = 1;
    public static final int RESTORE_SUCCESS = 2;
    public static final int BACKUP_ERROR = 3;
    public static final int RESTORE_NOFILEERROR = 4;
    public static final String COMMAND_BACKUP = "backupDatabase"; // cmd for backup databse
    public static final String COMMAND_RESTORE = "restoreDatabase"; // cmd for restore the database
    private Context mContext;
    private CompletionListener listener;
    public BackAsyncTask(Context context) {
        super();
        mContext = context;
    }
    public void setCompletionListener(CompletionListener aListener) {
        listener = aListener;
    }
    @Override
    protected Integer doInBackground(String... params) {
// inside doinbackground creating directry for backup file and copy the file
        File dbFile = mContext.getDatabasePath("mydb");
        File exportDir = new File(Environment.getExternalStorageDirectory(), "myAppBackups");
        if (!exportDir.exists()) {
            exportDir.mkdirs();
        }
        File backup = new File(exportDir, dbFile.getName());
        String command = params[0];
        if(command.equals(COMMAND_BACKUP)) {
            try {
                backup.createNewFile();
                fileCopy(dbFile, backup);
                return BACKUP_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else if(command.equals(COMMAND_RESTORE)) {
            try {
                if(!backup.exists()) {
                    return RESTORE_NOFILEERROR;
                }
                dbFile.createNewFile();
                fileCopy(backup, dbFile);
                return RESTORE_SUCCESS;
            } catch (IOException e) {
                return BACKUP_ERROR;
            }
        } else {
            return BACKUP_ERROR;
        }
    }
   
    @Override
    protected void onPostExecute(Integer result) {

        switch(result) {
// result for back up success
        case BACKUP_SUCCESS:
            if(listener != null) {
                listener.onBackupComplete();
            }
            break;
        case RESTORE_SUCCESS:
            if(listener != null) {
                listener.onRestoreComplete();
            }
            break;
        case RESTORE_NOFILEERROR:
            if(listener != null) {
                listener.onError(RESTORE_NOFILEERROR);
            }
            break;
        default:
            if(listener != null) {
                listener.onError(BACKUP_ERROR);
            }
        }
    }
    // this method for copying the file  source to disetination
    private void fileCopy(File source, File dest) throws IOException {
        FileChannel inChannel = new FileInputStream(source).getChannel();
        FileChannel outChannel = new FileOutputStream(dest).getChannel();
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }
Download FullSourecode
  b) Notification Activity
A class that represents how a persistent notification is to be presented to the user using the NotificationManager.
The Notification.Builder has been added to make it easier to construct Notifications.
This Notification Activity for notify any task completed.
 Sample Code 


 
/**
* * @author vijayakumar
*
*/
public class AndroidMADQAActivity extends Activity implements View.OnClickListener {
private static final int NOTE_ID = 100;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button button = new Button(this);
button.setText("Click New Notification");
button.setOnClickListener(this);
setContentView(button);
}
@Override
public void onClick(View v) {
handler.postDelayed(task, 10000);
Toast.makeText(this, "Notification will Appear in 10 seconds", Toast.LENGTH_SHORT).show();
}
private Handler handler = new Handler();
private Runnable task = new Runnable() {
@Override
public void run() {
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent launchIntent = new Intent(getApplicationContext(), AndroidMADQAActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent, 0);
Notification note = new Notification(R.drawable.ic_launcher, "Download Completed", System.currentTimeMillis());
note.setLatestEventInfo(getApplicationContext(), "Finished!", "Click Here!", contentIntent);
note.defaults |= Notification.DEFAULT_SOUND;
note.flags |= Notification.FLAG_AUTO_CANCEL;
manager.notify(NOTE_ID, note);
}
};
}

C).Timer Activity
 Timer activity class  represents will keep updating current time using timer task.
Sampe code .


 import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.TextView;
/**
 *
 * @author vijayakumar
 *
 */
public class AndroidMADQAActivity extends Activity {  
    TextView mClock;   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mClock = new TextView(this);
        setContentView(mClock);
    } 
    private Handler mHandler = new Handler();
    private Runnable timerTask = new Runnable() {
        @Override
        public void run() {
            Calendar now = Calendar.getInstance();
            mClock.setText(String.format("%02d:%02d:%02d",
                    now.get(Calendar.HOUR),
                    now.get(Calendar.MINUTE),
                    now.get(Calendar.SECOND)) );
            mHandler.postDelayed(timerTask,1000);
        }
    };
    @Override
    public void onResume() {
        super.onResume();
        mHandler.post(timerTask);
    }
    @Override
    public void onPause() {
        super.onPause();
        mHandler.removeCallbacks(timerTask);
    }

}

1 comment:

Check out this may be help you

Related Posts Plugin for WordPress, Blogger...