Tuesday 4 December 2012

BackPress click event with Confirmation dialogbox

Put this method in your activity.


@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Handle the back button
        if (keyCode == KeyEvent.KEYCODE_BACK) {
     
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View popuplayoutReject = inflater.inflate(R.layout.popup_reject_request, (ViewGroup) findViewById(R.id.popup_element));
        final PopupWindow popUpReject = new PopupWindow(popuplayoutReject, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT, false);
        ImageButton btnPopupReject_Ok, btnPopUpReject_Cancel;
        TextView txtRequestRejectMessage = (TextView) popuplayoutReject.findViewById(R.id.errorMessage);
        txtRequestRejectMessage.setText(getResources().getString(R.string.AddEntryNotSaved));
        btnPopupReject_Ok = (ImageButton) popuplayoutReject.findViewById(R.id.btnPopup_Yes);
        btnPopupReject_Ok.setImageResource(R.drawable.yes_button);
        
        btnPopupReject_Ok.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               finish();
            }
        });

        btnPopUpReject_Cancel = (ImageButton) popuplayoutReject.findViewById(R.id.btnPopUp_No);
        btnPopUpReject_Cancel.setImageResource(R.drawable.no_button);
        btnPopUpReject_Cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popUpReject.dismiss();
            }
        });
        popUpReject.showAtLocation(popuplayoutReject, Gravity.CENTER, 0, 0);
        return true;
        }
        return super.onKeyDown(keyCode, event);
    }

Detect OnClick of Webpage in WebView android



public class MainActivity extends Activity {
private WebView webview;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        webview = (WebView) findViewById(R.id.webView1); // Declare webview in .xml file
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("http://www.YOURWEBLINK.com/mpages//advertise/");
}
@Override
   public boolean onKeyDown(int keyCode, KeyEvent event) {
       if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
           webview.goBack();
           return true;
       }
       return super.onKeyDown(keyCode, event);
   }
   private class HelloWebViewClient extends WebViewClient {
       @Override
       public boolean shouldOverrideUrlLoading(WebView view, String url) {
           if(url.startsWith("mailto:")){
               MailTo mt = MailTo.parse(url);
               Intent intent = new Intent (Intent.ACTION_VIEW , Uri.parse("mailto:" + "contactus@YourDomain.com"));// MAIL SEND TO
               intent.putExtra(Intent.EXTRA_SUBJECT, "Subject"); // SUBJECT
               intent.putExtra(Intent.EXTRA_TEXT, "Please refer www.macmaker.blogspot.com for more details...Thanks RONAK PANDYA ");// Mail Detail
               startActivity(intent);
               view.reload();
               return true;
           }
 
               else{
                   view.loadUrl(url);
               }
               return true;
           }
       };
     //  mWebView.setWebViewClient(mWebClient);        }
   }
   

Tuesday 27 November 2012

Get the Width and Height of screen in android


public class MainActivity extends Activity {
private TextView tvheight, tvwidth;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tvheight = (TextView) findViewById(R.id.textView1);
tvwidth = (TextView) findViewById(R.id.textView2);

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int height = metrics.heightPixels;
int width = metrics.widthPixels;

tvheight.setText("Height --> " + String.valueOf(height));
tvwidth.setText("  Width --> " + String.valueOf(width));

}

}

Wednesday 21 November 2012

Getting source code from an APK file in android


Procedure to decoding .apk files and getting source code ---->

Step 1:
Make a new folder and put .apk file (which you want to decode) now rename this .apk file with extension .zip (eg:rename from filename.apk to filename.apk.zip) and save it..now you get classes.dex files etc...at this stage you are able to see drawable but not xml and java file...so continue...(You will get xml files but that will be encoded files not showing xml code drawable dir only)

Step 2:
Now extract this zip apk file in the same folder(in this eg or case NEW FOLDER). now dowmload dex2jar from this link http://code.google.com/p/dex2jar/ and extract it to the same folder (in this case NEW FOLDER).....now open command prompt and reach to that folder (in this case NEW FOLDER)....after reaching write dex2jar classes.dex and press enter.....now you get classes.dex.dex2jar file in the same folder......now download java decompiler from http://java.decompiler.free.fr/?q=jdgui and now double click on jd-gui and click on open file then open classes.dex.dex2jar file from that folder...now you get class file...save all these class file (click on file then click "save all sources" in jd-gui)..by src name....at this stage you get source...but xml files are still unreadable...so cont...

Step 3:
Now open another new folder and put these files
put .apk file which you want to decode
download 1. apktool v1.x & 2. apktool install window from google, and put both files in the same folder.
download framework-res.apk file using google and put in the same folder (Not all apk file need framework-res.apk file)
Open a command window
Navigate to the root directory of APKtool and type the following command: apktool if framework-res.apk
apktool d "apkname".apk ("apkname" denotes filename which you want to decode)
now you get a file folder in that folder and now you can easily read xml files also.

Step 4:
It's not any step just copy contents of both folder(in this case both new folder)to the single one
and enjoy with source code...

Ref : http://stackoverflow.com/questions/3593420/android-getting-source-code-from-an-apk-file?answertab=votes#tab-top

Enjoy Ronak Pandya

Thursday 18 October 2012

Eclipse Shortcuts


Eclipse Keyboard Shortcuts


1)      Ctrl + T for finding class even from jar

This keyboard shortcut in Eclipse is my most used and favorite shortcut. While working with high speed trading system which has complex code I often need to find classes with just blink of eye and this eclipse keyboard shortcut is just made for that. No matter whether you have class in your application or inside any JAR, this shortcut will find it.

2)      Ctrl + R for finding any resource (file) including config xml files

This is similar to above Eclipse shortcut with only difference that it can find out not only Java files but any files including xml, configs and many others, but this eclipse shortcut only finds files from your workspace and doesn’t dig at jar level.

3)      Ctrl + 1 for quick fix

This is another beautiful Eclipse shortcut which can fix up any error for you in Eclipse. Whether it’s missing declaration, missing semi colon or any import related error this eclipse shortcut will help you to quickly short that out.

4)      Ctrl + Shift + o for organize imports

Another Eclipse keyboard shortcut for fixing missing imports. Particularly helpful if you copy some code from other file and what to import all dependencies.

Eclipse Shortcut for Quick Navigation

In this section we will see some eclipse keyboard shortcut which helps to quickly navigate within file and between file while reading and writing code in Eclipse.

7) Ctrl + o for quick outline going quickly to method
9) Alt + right and Alt + left for going back and forth while editing.
12) Alt + Shift + W for show in package explorer
13) Ctrl + Shift + Up and down for navigating from member to member (variables and methods)
15) Ctrl + k and Ctrl + Shift +K for find next/previous
24) Go to a type declaration: F3, This Eclipse shortcut is very useful to see function definition very quickly.


Eclipse Shortcut for Editing Code

These Eclipse shortcuts are very helpful for editing code in Eclipse.
5) Ctrl + / for commenting, un commenting lines and blocks
6) Ctrl + Shift + / for commenting, un commenting lines with block comment
8) Selecting class and pressing F4 to see its Type hierarchy
10) Ctrl + F4 or Ctrl + w for closing current file
11) Ctrl+Shirt+W for closing all files.
14) Ctrl + l go to line
16) Select text and press Ctrl + Shift + F for formatting.
17) Ctrl + F for find, find/replace
18) Ctrl + D to delete a line
19) Ctrl + Q for going to last edited place


Miscellaneous Eclipse Shortcuts

These are different Eclipse keyboard shortcuts which doesn’t fit on any category but quite helpful and make life very easy while working in Eclipse.

20) Ctrl + T for toggling between super type and subtype
21) Go to other open editors: Ctrl + E.
22) Move to one problem (i.e.: error, warning) to the next (or previous) in a file: Ctrl +. For next, and Ctrl +, for previous problem
23) Hop back and forth through the files you have visited: Alt + ? and Alt + ?, respectively.
25) CTRL+Shift+G, which searches the workspace for references to the selected method or variable
26) Ctrl+Shift+L to view listing for all Eclipse keyboard shortcuts.
27) Alt + Shift + j to add javadoc at any place in java source file.
28) CTRL+SHIFT+P to find closing brace. Place the cursor at opening brace and use this.
29) Alt+Shift+X, Q to run Ant build file using keyboard shortcuts in Eclipse.
30) Ctrl + Shift +F for Autoformating.

Show/Hide android soft keybord in android



// SHOW KEYBOARD
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
 imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

// HIDE KEYBOARD
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0);

OR
// HIDE KEYBOARD
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS,0);
 

Friday 15 June 2012

Put & (Ampercend) sign in Android XML file


eg.
android:text="Rock & Roll Dance"

Set Any type of font in your application


Download .ttf file of the font which you like


Go to computer font (I’ve windows 7) and copy shruti font.
Paste it in android assets folder.
Use it in TextView.


Following is a code that can help you:


TextView detailText = (TextView) findViewById(R.id.detailText);
Typeface font = Typeface.createFromAsset(getAssets(), “SHRUTI.TTF”);
detailText.setTypeface(font);

Get Height and Weidth in android


int width,height;
Display display = getWindowManager().getDefaultDisplay();
        width = display.getWidth();
        height = display.getHeight();

CHECK EMAIL VALIDATIONS IN ANDROID


This is a simple example showing email validation in ANDROID.
This example uses regex for email validation.
Create a button and an edittext in your main.xml file and try this code.




import java.util.regex.Pattern;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class EmailValidationDemo extends Activity   {

    EditText TF;
    public Button checkButton;

    public final Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
              "[a-zA-Z0-9+._%-+]{1,256}" +
              "@" +
              "[a-zA-Z0-9][a-zA-Z0-9-]{0,64}" +
              "(" +
              "." +
              "[a-zA-Z0-9][a-zA-Z0-9-]{0,25}" +
              ")+"
          );
     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

       TF=(EditText) findViewById(R.id.TF);
       checkButton=(Button) findViewById(R.id.checkButton);

        checkButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
               String email=TF.getText().toString();
               if(checkEmail(email))
                  Toast.makeText(EmailValidationDemo.this,"Valid Email Addresss", Toast.LENGTH_SHORT).show();
               else
                  Toast.makeText(EmailValidationDemo.this,"Invalid Email Addresss", Toast.LENGTH_SHORT).show();
        }
        });
    }
    private boolean checkEmail(String email) {
        return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
    }
}



Refresh button in Android




btn_Refresh.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
// TODO Auto-generated method stub
// REFRESH CODE
RefreshPageActivity.this.startActivity(getIntent());
}
});

Delete SPACE from EditText(User cant add space in beginning in edittext if user presses space)


Step-1: Add "implements TextWatcher" after Activity
eg. public class AddMoreWebsite extends Activity implements TextWatcher {


Step-2:Now Put Cursor on Red line error and Add UnImplemented methods of TextWatcher.
Eg. it Will add following Methods


public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
String result = s.toString().replaceAll(" ", "");
if (!s.toString().equals(result)) {
et_AddMoreSite.setText(result);
et_AddMoreSite.setSelection(result.length());


}
}


public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub


}


public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub


}


Step-3: Now Add following lines in afterTextChanged(...)


String result = s.toString().replaceAll(" ", "");
if (!s.toString().equals(result)) {
et_AddMoreSite.setText(result);
et_AddMoreSite.setSelection(result.length());




Step-4: Now Put this line in onCreate() after your editText declaration.


et_AddMoreSite.addTextChangedListener(this);




Ref. Link: http://stackoverflow.com/questions/9757991/how-to-delete-instantly-space-from-an-edittext-if-a-user-presses-the-space


Enjoy.....

Awake Screen(Screen On) when starting activity




First import this file
import android.view.WindowManager.LayoutParams;


call this method whenever you need to On the screen
 private void unlockScreen() {
        Window window = this.getWindow();
        window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
        window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
    }

Friday 18 May 2012

Put Timer in android


import java.util.Timer;
import java.util.TimerTask;
import android.os.Handler.Callback;
import android.app.Activity;
import android.content.Intent;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

public class Timerscreen extends Activity{

    Button   btn_end;

    TextView  tv_callDuration;
    String nm,num;
   
   
     long starttime = 0;
        //this  posts a message to the main thread from our timertask
        //and updates the textfield
       final Handler h = new Handler(new Callback() {
            public boolean handleMessage(Message msg) {
               long millis = System.currentTimeMillis() - starttime;
               int seconds = (int) (millis / 1000);
               int minutes = seconds / 60;
               seconds     = seconds % 60;

               tv_callDuration.setText(String.format("%d:%02d", minutes, seconds));
                return false;
            }
        });
       //runs without timer be reposting self
       Handler h2 = new Handler();
       Runnable run = new Runnable() {

            public void run() {
               long millis = System.currentTimeMillis() - starttime;
               int seconds = (int) (millis / 1000);
               int minutes = seconds / 60;
               seconds     = seconds % 60;

               tv_callDuration.setText(String.format("%d:%02d", minutes, seconds));

               h2.postDelayed(this, 500);
            }
        };

       //tells handler to send a message
       class firstTask extends TimerTask {

            @Override
            public void run() {
                h.sendEmptyMessage(0);
            }
       };

       //tells activity to run on ui thread
       class secondTask extends TimerTask {

            @Override
            public void run() {
                CallSecondScreen.this.runOnUiThread(new Runnable() {

                    public void run() {
                       long millis = System.currentTimeMillis() - starttime;
                       int seconds = (int) (millis / 1000);
                       int minutes = seconds / 60;
                       seconds     = seconds % 60;

                       tv_callDuration.setText(String.format("%d:%02d", minutes, seconds));
                    }
                });
            }
       };


       Timer timer = new Timer();
   
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.second_calling_screen);
       
        btn_end = (Button)findViewById(R.id.btn2_endCall);
        tv_callDuration = (TextView)findViewById(R.id.tv_callDuration);
       
       
        starttime = System.currentTimeMillis();
        timer = new Timer();
        timer.schedule(new firstTask(), 0,500);
        timer.schedule(new secondTask(),  0,500);
        h2.postDelayed(run, 0);
   
       
        btn_end.setOnClickListener(new OnClickListener() {
           
            public void onClick(View v) {
                // TODO Auto-generated method stub
               
            finish();
               
               
            }
        });
    }
}

Play Alaram in android

public void PlayRingtone()
    {
   
        long ringDelay = 5000;
        Uri notification = RingtoneManager
        .getDefaultUri(RingtoneManager.TYPE_ALARM);
         alarmRingtone = RingtoneManager
        .getRingtone(getApplicationContext(), notification);
        alarmRingtone.play();
       
       
        TimerTask task = new TimerTask() {
        @Override
        public void run() {
        //alarmRingtone.stop();
        }
        };
        Timer timer = new Timer();
        timer.schedule(task, ringDelay);

       
    }

call this mathod whenever you needed....
Njoy...Ronak Pandya.....

Marquee text in android

Yes it is possible to make marquee text in android using following way....

Step -1 Create Textview in xml file 

<TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                
                android:ellipsize="marquee"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:freezesText="true"
                android:marqueeRepeatLimit="marquee_forever"
                android:scrollHorizontally="true"
                android:singleLine="true"
     
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="#717C40"
                android:textSize="11pt"
                android:textStyle="bold"
                android:typeface="monospace" />

Step-2 in your Activity file use following code

// MARQUEE CODE FOR TEXT VIEW
        TextView tv = (TextView) this.findViewById(R.id.textView1);
        tv.setEllipsize(TruncateAt.MARQUEE);
        tv.setText("         Ronak Ashvin Pandya- macmaker.blogspot.in                              ");
        tv.setSelected(true);


its done.....Njoy Ronak Pandya

Give Effects to Buttons in android

To give effect Like we feel that button has been pressed in our application, use following code.
create one xml file in your drawable directory(or where you put your images). paste this code in it and call this file in your buttons background.

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">

// Button Focused Pressed
<item android:state_focused="true"
android:state_pressed="true"
android:drawable="@drawable/call_end_2" />
// Button Pressed
<item android:state_focused="false"
android:state_pressed="true"
android:drawable="@drawable/call_end_1" />
// Button Default Image
<item android:drawable="@drawable/call_end" />
</selector>
now call this file in your xml file i.e 

<Button
            android:id="@+id/btn_startcall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/your_button_efffect_xml" />
   

Thursday 17 May 2012

Integrate Advertisement in android (Ads)

To integrate Ads in your application 
Step-1 you need to create Linear layout of 320x50 size see this code

 <LinearLayout
                xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
                android:id="@+id/mainLayout"
                android:layout_width="320dp"
                android:layout_height="50dp"
                android:orientation="vertical" >
            </LinearLayout>


Step-2 Integrate GoogleAdMobAdsSdk-6.0.0.jar file which is available on internet.
Now Paste this .Jar file in your Project.
now,
integrate it using (Right click on Android Project --> Properties --> Java Build path --> Libraries --> Add Jars --> select your project and select  GoogleAdMobAdsSdk-6.0.0.jar file --> now select Order and Export --> Select All --> Ok


Step-3 Give Internet and Network Access Permission from Manifest.xml file

Step-4 Put this code in Manifest file under application tag.
 <activity
            android:name="com.google.ads.AdActivity"
             android:screenOrientation="portrait"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />


 Step-5 Open Project Properties file and change target to 14 or higher.
# Project target.
target=android-14



Step-6 Put this method in your Activity file and call wherever you want to show Ads.



public void DisplayAds() {
// Create the adView
adView = new AdView(this, AdSize.BANNER, "YOUR KEY");
// adView .setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
// LayoutParams.WRAP_CONTENT));


// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="@+id/mainLayout"
LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);


// Add the adView to it
layout.addView(adView);
AdRequest re = new AdRequest();
re.setTesting(false);// this must be false when apps is released in the
// market
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());


}


NJOY--- RoNaK PaNdYa


Integrate Progress Dialog Box in android

To integrate progress dialog in android application, it shows dialog box and processing particular tasks in background. following is the code...njoy...


There are four processes in Progress dialog - 
1. onPreExecute - shows loading view to user, he cant interacts with screen.
2. doInBackground - all the processes runs in background of Loading screen of onPreExecute.
3. onProgressUpdate and - set the current progress of the progress dialog
4. onPostExecute - must contain  progressDialog.dismiss(); so that user can interacts with screen. if you want to set dynamic data which came from doInBackground method  you can put it here. so user can see it. 


Put following class in your main activity class. after completion of onCreate(). and call this in onCreate() or wherever you need to show dialog box and run process in background.


To call this class use ----->> new LoadViewTask().execute();



private class LoadViewTask extends AsyncTask<Void, Integer, Void> {
private static final int length = 0;


// Before running code in the separate thread
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(CheckWeb_Status.this,
"Loading...", "Loading, please wait...", false, false);


}


// The code to be executed in a background thread.
@Override
protected Void doInBackground(Void... params) {


//USER DEFINED PROCESSES THAT RUNS IN BACKGROUND ON PROGRESS DIALOG
                     // PROCESS-1
ParseJson(data);
ParseXml();


/*
* This is just a code that delays the thread execution 4 times,
* during 850 milliseconds and updates the current progress. This is
* where the code that is going to be executed on a background
* thread must be placed.
*/
try {
// Get the current thread's token
synchronized (this) {
// Initialize an integer (that will act as a counter) to
// zero
int counter = 0;
// While the counter is smaller than four
while (counter <= 4) {
// Wait 850 milliseconds
this.wait(850);
// Increment the counter
counter++;
// Set the current progress.
// This value is going to be passed to the
// onProgressUpdate() method.
publishProgress(counter * 25);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;


}


// Update the progress
@Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}


// after executing the code in the thread
@Override
protected void onPostExecute(Void result) {


// close the progress dialog
Log.v("Progress", "Entered");




                        //SET DATA CAME FROM doInBackground() PARSING
try {


if (json.getString(TAG_UMRP).toString().equals("")) {
tv_umrp.setText("MRnk : No MozRank found");
} else {
tv_umrp.setText(" MRnk  \t\t: " + json.getString(TAG_UMRP));
}


if (json.getString(TAG_UPA).toString().equals("")) {
tv_upa.setText("Page Authority : No Data found");
} else {
tv_upa.setText("Page Authority : "
+ json.getString(TAG_UPA));
}


if (json.getString(TAG_UPL).toString().equals("")) {
tv_upl.setText("Root Domain : No Root Domain found");
} else {
tv_upl.setText("Root Domain : " + json.getString(TAG_UPL));
}


Log.v("Progress", "Setted");


// THIS IS MUST progressDialog.dismiss();
progressDialog.dismiss();


} catch (Exception e) {


}
                  //SET DATA CAME FROM doInBackground() PARSING
tv_PageAlx.setText("Page Alexa \t\t: "
+ String.valueOf(AlexaData).replace("[", "")
.replace("]", ""));
System.out.println("Page alexa " + String.valueOf(AlexaData));
tv_PageRnk.setText("Page Rank \t\t: "
+ String.valueOf(RankData).replace("[", "")
.replace("]", ""));
System.out.println("Page Rank " + String.valueOf(RankData));
/*
* tv_CompeteRnk .setText("Compete Rank : " +
* String.valueOf(CompeteData).replace("[", "") .replace("]", ""));
*/
Log.d("Parsing", "Page Rank : " + RankData);
Log.d("Parsing", "Page Alexa : " + String.valueOf(AlexaData));


SendEmail(); // PROCESS RUNS IN BACKGROUND
}


}




Check Internet connection in android application

To check Internet connection is Ok or not? or which type of connection you are using i.e WiFi or GPRS etc...following is a code for that....njoy....and call this method in main onCreate() method.



void checkInternetConnectionStatus() {
ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);


android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);


android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);


if (wifi.isAvailable()) {
Toast.makeText(this, "Wi-Fi connection", Toast.LENGTH_LONG).show();
} else if (mobile.isAvailable()) {
Toast.makeText(this, "Mobile Internet", Toast.LENGTH_LONG).show();


} else {
/*
* Toast.makeText(this, "No Internet Connection", Toast.LENGTH_LONG)
* .show();
*/
new AlertDialog.Builder(this)
.setTitle("No internet connection active")
.setMessage(
"Please start internet connection and run this application.")
.setNegativeButton("Exit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Log.d("AlertDialog", "Negative");
finish();
}
}).show();
}
}

Tuesday 24 April 2012

Send Emails in Background in Android.without user interaction...



Step-1
First of all Download 3 Jar files from http://code.google.com/p/javamail-android/downloads/list. (Ref. "http://stackoverflow.com/questions/2020088/sending-email-in-android-using-javamail-api-without-using-the-default-android-a")
activation.jar
additional.jar
mail.jar

Step-2
copy and paste those jar files into your project. then
Integrate all above jar files into your project
Right click on your project --> Properties -->
Java Build path --> Libraries --> Add JARs--> Add all 3 jars

Now go to Next Tab "Order and Export"--> select all --> Ok

Step-3
Create one class

import java.util.Date;
import java.util.Properties;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class GMailSender extends javax.mail.Authenticator {
    private String _user;
      private String _pass;
   
      private String[] _to;
      private String _from;
   
      private String _port;
      private String _sport;
   
      private String _host;
   
      private String _subject;
      private String _body;
   
      private boolean _auth;
      
      private boolean _debuggable;
   
      private Multipart _multipart;
   
   
      public GMailSender() {
        _host = "smtp.gmail.com"; // default smtp server
        _port = "465"; // default smtp port
        _sport = "465"; // default socketfactory port
   
        _user = ""; // username
        _pass = ""; // password
        _from = ""; // email sent from
        _subject = ""; // email subject
        _body = ""; // email body
   
        _debuggable = false; // debug mode on or off - default off
        _auth = true; // smtp authentication - default on
   
        _multipart = new MimeMultipart();
   
        // There is something wrong with MailCap, javamail can not find a handler for the multipart/mixed part, so this bit needs to be added.
        MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
        mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
        mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
        mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
        mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
        mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
        CommandMap.setDefaultCommandMap(mc);
      }
   
      public GMailSender(String user, String pass) {
        this();
   
        _user = user;
        _pass = pass;
      }
   
      public boolean send() throws Exception {
        Properties props = _setProperties();
   
        if(!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") && !_subject.equals("") && !_body.equals("")) {
          Session session = Session.getInstance(props, this);
   
          MimeMessage msg = new MimeMessage(session);
   
          msg.setFrom(new InternetAddress(_from));
          
          InternetAddress[] addressTo = new InternetAddress[_to.length];
          for (int i = 0; i < _to.length; i++) {
            addressTo[i] = new InternetAddress(_to[i]);
          }
            msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
   
          msg.setSubject(_subject);
          msg.setSentDate(new Date());
   
          // setup message body
          BodyPart messageBodyPart = new MimeBodyPart();
          messageBodyPart.setText(_body);
          _multipart.addBodyPart(messageBodyPart);
   
          // Put parts in message
          msg.setContent(_multipart);
   
          // send email
          Transport.send(msg);
   
          return true;
        } else {
          return false;
        }
      }
   
      public void addAttachment(String filename) throws Exception {
        BodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
   
        _multipart.addBodyPart(messageBodyPart);
      }
   
      @Override
      public javax.mail.PasswordAuthentication getPasswordAuthentication() {
        return  new javax.mail.PasswordAuthentication(_user,_pass);
      }
   
      private Properties _setProperties() {
        Properties props = new Properties();
   
        props.put("mail.smtp.host", _host);
   
        if(_debuggable) {
          props.put("mail.debug", "true");
        }
   
        if(_auth) {
          props.put("mail.smtp.auth", "true");
        }
   
        props.put("mail.smtp.port", _port);
        props.put("mail.smtp.socketFactory.port", _sport);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
   
        return props;
      }
   
      // the getters and setters
      public String getBody() {
        return _body;
      }
   
      public void setBody(String _body) {
        this._body = _body;
      }

    public String[] get_to() {
        return _to;
    }

    public void set_to(String[] _to) {
        this._to = _to;
    }

    public String get_from() {
        return _from;
    }

    public void set_from(String _from) {
        this._from = _from;
    }

    public String get_subject() {
        return _subject;
    }

    public void set_subject(String _subject) {
        this._subject = _subject;
    }
   
    }


Step-4

in your Main class

public class GMailMain extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        Button addImage = (Button) findViewById(R.id.send);
        addImage.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
               
               
                GMailSender mailsender = new GMailSender("sender@gmail.com", "password123");

                String[] toArr = { "receiver1@gmail.com", "receiver2@gmail.com" };
                mailsender.set_to(toArr);
                mailsender.set_from("sender@gmail.com");
                mailsender.set_subject("This is an email sent using my Mail JavaMail wrapper from an Android device.");
                mailsender.setBody("Email body.");

                try {
                    //mailsender.addAttachment("/sdcard/filelocation");

                    if (mailsender.send()) {
                        Toast.makeText(GMailMain.this,
                                "Email was sent successfully.",
                                Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(GMailMain.this, "Email was not sent.",
                                Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                   
                    Log.e("MailApp", "Could not send email", e);
                }
            }
        });

    }
}