Wednesday, January 9, 2013

Logout and Exit from previous activity in android


Mostly of time, We facing a challenge in android when we creating session base application, in which we need to save login credentials through out application and after click on logout need to finish all previous activities those are using session values.
for save login credential in application used SharedPreferences, SQLite database or external file writing in SD card and more info see Android Storage guide
and in case of logout just remove all values from the SharedPreferences and redirect to login screen but when am click back from android mobile button, last activity restore. How prevent this,?
just add some code of lines in onRestart function in activity class at which you want to check session keys,
see below code of lines
@Override
 protected void onRestart() {
  // TODO Auto-generated method stub
  super.onRestart();
  SharedPreferences pref = context.getApplicationContext().getSharedPreferences("samplekey", Context.MODE_PRIVATE);
  if (pref.getString("<login key name>", "").length()==0) {
      finish();  
  }
 }
whenever you click back button from android mobile , every time onRestart method of previous activity/screen class called and checking about session,
if session not exist than it's finish the activity otherwise open that screen/activity

Catch Home button pressed in Android


searching about how Catch Home button pressed in Android, lot of blogs, technics and method implemented by different- different developer but not sccess for this home button catching... some of the blogs and post says you can't catch Home button click in android due to security and user safety .
finally i found and implement a method to detect home button click and notify user for that see below code samples
for saving info in android am using SharedPreferences so a Session class structure to save all info

public class Session {

 private SharedPreferences pref;
 private Editor editor;
 private String KEY = "sampletest";

 public Session(Context context) {
  // TODO Auto-generated constructor stub
  pref = context.getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
  editor = pref.edit();
 }

 public void savePreferenceData(String key, String value) {
  editor.putString(key, value);
  editor.commit();
 }

 public String getPreferenceData(String key) {
  return pref.getString(key, "");
 }
 
 public void clearall(){
  editor.clear();
  editor.commit();
 }
 
}


now create a common class structure that having technics to detects Home button clicks
public class Common extends Activity{

 private Session presession;
 private Boolean startactivitys;
 private Boolean UserLeaveHints;
 

 @Override
 protected void onResume() {
  // TODO Auto-generated method stub
  super.onResume();
  startactivitys = false;
  UserLeaveHints = false;
  System.out.println(this+" onResume ");
 }

 
 @Override
 public void startActivity(Intent intent) {
  // TODO Auto-generated method stub
  super.startActivity(intent);
  System.out.println(this+" startActivity ");
  startactivitys = true;
  presession = new Session(this);
  presession.savePreferenceData("onBackPressed", String.valueOf(false));
 }

 @Override
 protected void onStop() {
  // TODO Auto-generated method stub
  super.onStop();
  System.out.println(this+" onStop ");
  presession = new Session(this);
  boolean temp = presession.getPreferenceData("onBackPressed")!=null ? 
    Boolean.parseBoolean(presession.getPreferenceData("onBackPressed")):false;
  System.out.println("previous backpress "+temp);
  if(temp && UserLeaveHints){
   Toast.makeText(this, "app leaving", Toast.LENGTH_SHORT).show();
   System.out.println("++++++++++++++app leaving++++++++++++++++");
  }
  if(!startactivitys && UserLeaveHints){
   Toast.makeText(this, "app leaving", Toast.LENGTH_SHORT).show();
   System.out.println("++++++++++++++app leaving++++++++++++++++");
  }
 }

 @Override
 protected void onUserLeaveHint() {
  // TODO Auto-generated method stub
  super.onUserLeaveHint();
  System.out.println(this+" onUserLeaveHint ");
  UserLeaveHints = true;
 }

 @Override
 public void onBackPressed() {
  // TODO Auto-generated method stub
  super.onBackPressed();
  System.out.println(this+" onBackPressed ");
  presession = new Session(this);
  presession.savePreferenceData("onBackPressed", String.valueOf(true));
 }

 
}
see onStop function having Toast notification, that's show notification to user when user click on home and leaving application safely
One Question arising in mind how use this in your project ?
just simple extent this common class with your activity class instead of extending with activity .. and create Session as mention .
now you test this and provide feedback

Thursday, November 15, 2012

Download mails from all Folders via IMAPS protocol

In previous post am mention about how download mails from gmail server

than new question occurs how download all mail from all folder like spam, important, sent, draft etc
first need to list out all folder exist in your mail account by this
Folder[] folder = store.getDefaultFolder().list("*");

output some thing like this
INBOX
Notes
Personal
Receipts
Travel
Work
[Gmail]/All Mail
[Gmail]/Drafts
[Gmail]/Important
[Gmail]/Sent Mail
[Gmail]/Spam
[Gmail]/Starred
[Gmail]/Trash

and than extract all mail from the folder and same mail in eml format see below code

import java.io.File;
import java.io.FileOutputStream;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;

public class test {


public static long start;

public static void main(String args[]) throws Exception {

 Store store = null;
 Folder[] folder = null;
 try {
  start = System.currentTimeMillis();
  Properties props = System.getProperties();
  props.setProperty("mail.store.protocol", "imaps");
  Session session = Session.getDefaultInstance(props, null);
  session.setDebug(true);
  store = session.getStore("imaps");
  store.connect("imap.gmail.com", "--mail id--", "--password--");
  folder = store.getDefaultFolder().list("*");
  for (javax.mail.Folder folder1 : folder) {
            if ((folder1.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
                System.out.println(folder1.getFullName() + ": " + folder1.getMessageCount());
                folder1.open(Folder.READ_ONLY);
                for(Message msg : folder1.getMessages()){
                 
                 File ff = new File("C:/Desktop/mails", "msg/"+folder1.getFullName());
                 if(!ff.exists())
                  ff.mkdirs();
                 File emlFile = new File(ff.getAbsolutePath()+System.getProperty("file.separator")+msg.getHeader("message-id")[0].replace("<", "").replace(">", "")+".eml");
                 emlFile.createNewFile();
                 msg.writeTo(new FileOutputStream(emlFile));
                }
                
                if (folder1 != null) {
                    try {
                     folder1.close(true);
                    } catch (MessagingException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
                    }
                   }
            }
        }
  
 } catch (Exception e) {
  // TODO: handle exception
  e.printStackTrace();
 } finally {
  if (store != null) {
   try {
    store.close();
   } catch (MessagingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  long end = System.currentTimeMillis() - start;
  System.out.println("--- Done: , end: " + end + "ms");
 }
 }

}

Saturday, November 10, 2012

Record Video And PlayBack In android

Let us know how record video with audio in andriod .

Firstly device must have in-built camera with device for that use a uses-feature tag in AndroidManifest file
<uses-feature android:name="android.hardware.camera" />

and some permission are required to use camera or write a file in External storage
<uses-permission android:name="android.permission.CAMERA"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>

android.view.SurfaceView hold the android camera object and android.media.MediaRecorder object records the video and audio and export the file in java.io.File In Android having two camera rear and front camera, which one can select, for that we use front camera ... by following code
CameraInfo cameraInfo = new CameraInfo(); 
int cameraCount = Camera.getNumberOfCameras();
if(cameraCount >1)
for ( int camIdx = 0; camIdx < Camera.getNumberOfCameras(); camIdx++ ) { 
       Camera.getCameraInfo( camIdx, cameraInfo ); 
       if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT  ) { 
           try { 
            prCamera = Camera.open( camIdx ); 
           } catch (RuntimeException e) { 
               Log.i("Camera failed to open: ",e.getLocalizedMessage()); 
           } 
       } 
   }
In this example video encoded format is MPEG_4_SP, audio format is AMR_NB, and period of recording is 2 minutes and output file name create it by this function
String.valueOf(System.currentTimeMillis()) +".mp4"
after recording PlayVideo.java is used for play video file inside the android.widget.VideoView

Whole source of this post avaiable at my github Repository VideoRecording

Tuesday, November 6, 2012

Fetch Android Contact

How fetch contact in android ?
contact save in phone memory and also in sim memory . 
To fetch  list of contact, first add permission in android manifest file for read contact like this

<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>

in android all contact store in contact database for fetch need to fetch contact from database using cursor see sample code below
Cursor c = this.managedQuery(ContactsContract.Data.CONTENT_URI, null,
  Data.MIMETYPE + "=?", 
  new String[] { ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE },
  null);
while (c.moveToNext()) {
 int type = c.getInt(c.getColumnIndex(Phone.TYPE));
 if (type == Phone.TYPE_MOBILE) {
  Log.i("contact name",c.getString(c.getColumnIndex(Contacts.DISPLAY_NAME)));, 
  Log.i("contact number",c.getString(c.getColumnIndex(Phone.NUMBER)));
   }
  }
c.close();
In result,  you see all contact in logcat.

Send SMS in Android

How send sms from android ?
for this you must mention sms send permission in android manifest file like this
<uses-permission android:name="android.permission.SEND_SMS" />
after that use this code for send sms to a mobile number

try {
    smsManager.sendTextMessage("--here mobile number--", null, "--here sms text--", null, null);
    Log.d("Mobile", mobile + " message sent");
 } catch (Exception ex) {
    Log.d("Mobile", "Could not send message to " + mobile);
}
sms receive by mobile if proper network available and sufficient balance available

Sunday, November 4, 2012

titanium notification in iphone and android

ANDROID---create notification and click on notification lunch
//android
var intent = Ti.Android.createIntent( {
  action : Ti.Android.ACTION_MAIN,
  className : Ti.App.id+'activity_name', // activity_name that save inside build\android\bin\classes folder in titanium project
  packageName : Ti.App.id
});
intent.addCategory(Titanium.Android.CATEGORY_LAUNCHER);
var pending = Ti.Android.createPendingIntent( {
    activity : Ti.Android.currentActivity,
    intent : intent,
    type : Ti.Android.PENDING_INTENT_FOR_ACTIVITY,
    flags : Ti.Android.FLAG_ACTIVITY_NO_HISTORY
});
var dateValue = new Date();
var notification = Ti.Android .createNotification( {
         contentIntent : pending,
         contentTitle : '--Title of noticaification--',
         contentText : '----message would you want to show------',
         when : dateValue.getTime(), //show timing in  notification
         icon : Ti.App.Android.R.drawable.appicon,
         flags : Titanium.Android.ACTION_DEFAULT | Titanium.Android.FLAG_AUTO_CANCEL | Titanium.Android.FLAG_SHOW_LIGHTS
});
//Ti.Android.NotificationManager.notify(Math.floor(Math.random() * 32, 767), notification);
Ti.Android.NotificationManager.notify(1, notification);
IPHONE---create local notification and click on ok button relunch application
//iphone
var notification = Ti.App.iOS.scheduleLocalNotification({
  alertBody:'-----message would you want to show------',
  alertAction:"OK",
  sound:"default",
  userInfo:{},//pass value to other screen use this userInfo field
  date:new Date(new Date().getTime() + 3000)// 3 seconds after backgrounding
});
for recieve that data that would be pass though notication ..write this code
 Ti.App.iOS.addEventListener('notification', function(d) {
   Ti.API.info('data received = ' + JSON.stringify(d));
 });