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();
}
}