You are on page 1of 50

ANDROID KOLEKSI CODE

int array[] = {1,2,3};


Intent i = new Intent(A.this, B.class);
i.putExtra("numbers", array);
startActivity(i);
Bundle extras = getIntent().getExtras();
int[] arrayB = extras.getIntArray("numbers");

import java.util.Timer;
import java.util.TimerTask;
long starttime = 0;
Timer timer = new Timer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xxx);
lihat();
final Handler h = new Handler(new Callback() {
@Override
public boolean handleMessage(Message msg) {
long millis = System.currentTimeMillis() - starttime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds
= seconds % 60;
if (minutes >=0 && seconds >=20){selesai();}
txtTimer.setText(String.format("Waktu Anda ini :"+"%d:%02d"+" (max=> 3:20)", minutes, seconds));
return false;
}
});
class firstTask extends TimerTask {
@Override
public void run() {h.sendEmptyMessage(0);}
};
starttime = System.currentTimeMillis();
timer.schedule(new firstTask(), 0,1000);
}// setContentView
public void selesai(){
new AlertDialog.Builder(this)
.setTitle("Selesai Angka")
.setMessage("Terimakasih... Anda Telah Melakukan tes TPA Angka")
.setNeutralButton("Tutup", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
finish();
timer.cancel();
timer.purge();
Intent i= new Intent(soal_angka.this, hasil.class);
i.putExtra("nama", sNama);
i.putExtra("usia", sUsia);
i.putExtra("jk", sJK);
i.putExtra("record", record);
i.putExtra("kategori", "Tes Angka");
i.putExtra("jumbenar", String.valueOf(jumbenar));
startActivity(i);
}})
.show();
}
int
o=
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;setRequestedOrientation(o);
int
o=
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;setRequestedOrientation(o);

Button
ImageView callImage = (ImageView) findViewById(R.id.pilGambar);

callImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent call= new Intent(getBaseContext(), registrasi.class);
call.putExtra("pesan", "register");
startActivity(call);
}
});
===============================================
=================
Button btnTelp=(Button)findViewById(R.id.detCall);
btnTelp.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String toDial="tel:"+telepon;
startActivity(new Intent(Intent.ACTION_DIAL,Uri.parse(toDial)));
}});
Button btnMap=(Button)findViewById(R.id.detMap);
btnMap.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("https://maps.google.com/maps?
saddr="+myLati+","+myLongi+"&daddr="+latitude+","+longitude));
startActivity(intent);
}});

getData
Intent call = this.getIntent();
String pesan=call.getStringExtra("pesan");
public void loading(){
new Thread() {
public void run() {
try{Thread.sleep(5000);}
catch (Exception e) {}
Intent i = new Intent(MainActivity.this, menu.class);
startActivity(i);
finish();
}
}.start();
}

<ProgressBar android:id="@+id/progress_horizontal"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="200dip"
android:layout_height="wrap_content"
android:max="100"
android:progress="50"
android:secondaryProgress="75" />

==========================================================
=================================
ProgressDialog progressBar;
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
public void LOADING100() {
progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("File downloading ...");// STYLE_SPINNER
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
progressBarStatus = 0;
fileSize = 0;
new Thread(new Runnable() {
public void run() {
while (progressBarStatus < 100) {
// process some tasks

progressBarStatus = doSomeTasks();
// your computer is too fast, sleep 1 second
try {Thread.sleep(1000);}
catch (InterruptedException e) {e.printStackTrace();}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run()
{progressBar.setProgress(progressBarStatus);}});}
// ok, file is downloaded,
if (progressBarStatus >= 100) {
// sleep 2 seconds, so that you can see the 100%
try {Thread.sleep(2000);}
catch (InterruptedException e) {e.printStackTrace();}
progressBar.dismiss();
}}}).start();
}
// file download simulator... a really simple
public int doSomeTasks() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {return 10;}
else if (fileSize == 200000) {return 20;}
else if (fileSize == 300000) {return 30;}
// ...add your own
}
return 100;
}

public void setSplash(){


final ProgressDialog myProgressDialog = ProgressDialog.show(main.this, "Loading", "Mohon
Tunggu...", true);
new Thread() {
public void run() {
try{Thread.sleep(5000);}
catch (Exception e) {}
Intent i = new Intent(main.this, Menu.class);
myProgressDialog.dismiss();
main.this.finish();
startActivity(i);
} }.start();
}

marquee
<TextView
android:id="@+id/txtMarquee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="selamat datang di aplikasi android "
android:textSize="14sp"
android:layout_x="3px"
android:layout_y="4px"
android:typeface="sans"
android:textColor="#0000ff"
android:background="#000000"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever">
</TextView>
void callMarquee(){
Calendar cal = Calendar.getInstance();
int jam = cal.get(Calendar.HOUR);
int menit= cal.get(Calendar.MINUTE);
int detik= cal.get(Calendar.SECOND);
int tgl= cal.get(Calendar.DATE);
int bln= cal.get(Calendar.MONTH);
int thn= cal.get(Calendar.YEAR);

String stgl=String.valueOf(tgl)+"-"+String.valueOf(bln)
+"-"+String.valueOf(thn);
String sjam=String.valueOf(jam)+":"+String.valueOf(menit)
+":"+String.valueOf(detik);
TextView txtMarquee=(TextView)findViewById(R.id.txtMarquee);
txtMarquee.setSelected(true);
String kata="Selamat Datang di Aplikasi Android
"+stgl+"/"+sjam+" #";
String
kalimat=String.format("%1$s",TextUtils.htmlEncode(kata));
txtMarquee.setText(Html.fromHtml(kalimat+kalimat+kalimat));
}

Play SONG:
MediaPlayer mp = MediaPlayer.create(this, R.raw.lonely);
if(!mp.isPlaying()){
mp.start();mp.setLooping(true);
Toast.makeText(this, "Play
Lagu....",Toast.LENGTH_LONG).show();

Message
import
import
import
import
import
import
import

android.content.DialogInterface;
android.content.DialogInterface.OnClickListener;
android.graphics.Bitmap;
android.graphics.BitmapFactory;
android.graphics.Color;
android.graphics.Matrix;
android.app.AlertDialog;

public void keluar(){


new AlertDialog.Builder(this)
.setTitle("Menutup Aplikasi")
.setMessage("Terimakasih... Anda Telah Menggunakan Aplikasi Ini")
.setNeutralButton("Tutup", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
finish();
}})
.show();
}
public void keluarYN(){
AlertDialog.Builder ad=new AlertDialog.Builder(formstuffkoleksi.this);
ad.setTitle("Konfirmasi");
ad.setMessage("Apakah benar ingin keluar?");
ad.setPositiveButton("OK",new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
keluar();
}});
ad.setNegativeButton("No",new OnClickListener(){
public void onClick(DialogInterface arg0, int arg1) {
}});
ad.show();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
keluarYN();
return true;
}
return super.onKeyDown(keyCode, event);
}

Menu
public boolean onCreateOptionsMenu(Menu menu) {

menu.add(0, 7, 0, "Aplikasi").setIcon(R.drawable.icon1);
menu.add(0,
1, 0, "Setting").setIcon(R.drawable.icon2);
menu.add(0, 2, 0, "Profil").setIcon(R.drawable.icon3);
menu.add(0,
3, 0, "Keluar").setIcon(R.drawable.keluar);
SubMenu subMenu = menu.addSubMenu("Mata Uang");//default 0
subMenu.add(1, 4, 0, "Dolar").setChecked(true);
subMenu.add(1, 5, 0, "Euro");
subMenu.add(1, 6, 0, "Pounds");
subMenu.setGroupCheckable(1, true, true);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 2: Toast.makeText(this, "You clicked O",Toast.LENGTH_LONG).show();
return true;
case 3: Toast.makeText(this, "You Keluar",Toast.LENGTH_LONG).show();
return true;
case 4: item.setChecked(true);jenis="Dollar";
Toast.makeText(this, "You clicked on Dollar",Toast.LENGTH_LONG).show();
return true;
case 5: item.setChecked(true);jenis="Euro";
Toast.makeText(this, "You clicked on Euro",Toast.LENGTH_LONG).show();
return true;
case 6: item.setChecked(true);jenis="Pounds";
Toast.makeText(this, "You clicked on Pounds",Toast.LENGTH_LONG).show();
return true;
}
return false;
}

public boolean onCreateOptionsMenu(Menu menu) {


menu.add(0, 1, 0, "Arsip").setIcon(R.drawable.keluar);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
Intent put= new Intent(getBaseContext(), listdataDB.class);
startActivity(put);
return true;
}
return false;
}

AutoCompleteTextView
<AutoCompleteTextView android:id="@+id/ltlahir" />
AutoCompleteTextView actvTlahir = (AutoCompleteTextView)
this.findViewById(R.id.ltlahir);
String[]pilPulau=new String[]
{"Sumatera","Jawa","Kalimantan","Sulawesi","Maluku","Irian Jaya"};
ArrayAdapter<String> tlahir = new
ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,pilP
ulau);
actvTlahir.setAdapter(tlahir);

spinner

<Spinner android:id="@+id/spinAgama" android:drawSelectorOnTop="true"


android:layout_width="wrap_content" android:layout_height="wrap_content"
/>
String[]pilAgama={"Islam","Kristen","Hindu","Budha","Kepercayaan"};
Spinner mySpin = (Spinner) findViewById(R.id.spinAgama);
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, pilAgama);
mySpin.setAdapter(adapter);
mySpin.setOnItemSelectedListener( new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2, long
arg3){
int index = mySpin.getSelectedItemPosition();
Toast.makeText(getBaseContext(),"Pilihan Anda : " + pilAgama[index],
Toast.LENGTH_SHORT).show();}
public void onNothingSelected(AdapterView<?> arg0){}
});

CheckBox
<CheckBox android:id="@+id/chkStatus"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Sudah Bekerja" />
final CheckBox chkStatus = (CheckBox) findViewById(R.id.chkStatus);
chkStatus.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {Toast.makeText(getBaseContext(), "Status
Selected", Toast.LENGTH_SHORT).show();}
else {Toast.makeText(getBaseContext(), "Status Not selected",
Toast.LENGTH_SHORT).show();}
}
});

TAB
public class formTabStd2Lp2mAray extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost host = this.getTabHost();
host.addTab(host.newTabSpec("one")
.setIndicator("APLIKASI", getResources().getDrawable(R.drawable.icon1))
.setContent(new Intent(this, profil.class)));
Intent intentCari= new Intent().setClass(this, tentang.class);
host.addTab(host.newTabSpec("two")
.setIndicator("PENCARIAN")
.setContent(intentCari));
host.addTab(host.newTabSpec("three")
.setIndicator("KOSAKATA")
.setContent(new Intent(this, profil.class)));
host.setCurrentTab(0);
}
}

LOAD WEB ASSET/URL


public class loadJqueryOL extends Activity {
WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.jquery);

webView = (WebView) findViewById(R.id.webview);


WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("file:///android_asset/jqueryoff.html");
return;
}

//letakkkan library di asset jg


//<link href="jquery.mobile-1.0.1.min.css" rel="stylesheet" type="text/css">
//<script src="jquery-1.6.4.min.js"></script>
//<script src="jquery.mobile-1.0.1.min.js"></script>
Web.xml
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none" />

LIST
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>

import
import
import
import
import
import
import
import
import
import

android.app.Activity;
android.content.Intent;
android.os.Bundle;
android.view.View;
android.widget.AdapterView;
android.widget.ArrayAdapter;
android.widget.ListView;
android.widget.Toast;
android.widget.AdapterView.OnItemClickListener;
android.widget.AdapterView.OnItemSelectedListener;

public class listlp2maray extends Activity {


ListView s1;
int jd=0;
String[] arrKursus;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
jd=3;
arrKursus=new String[jd];
arrKursus[0]="PHP dan Mysql";
arrKursus[1]="Desain Grafis";
arrKursus[2]="Matlab Advance";
s1=(ListView)findViewById(R.id.listView);
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, arrKursus);

s1.setAdapter(adapter);
s1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int p, long id) {
Toast.makeText(getBaseContext(), " Kursus pilihan Anda : " +
arrKursus[p],Toast.LENGTH_LONG).show();
Intent i = new Intent(listlp2maray.this, listlp2maray.class);
i.putExtra("kursus", arrKursus[p]);
startActivity(i);
}
});
s1.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onNothingSelected(AdapterView<?> arg0) {}
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int p,long arg3) {
Toast.makeText(getBaseContext(), " Kursus pilihan Anda : " +
arrKursus[p],Toast.LENGTH_LONG).show();
Intent i = new Intent(listlp2maray.this, listlp2maray.class);
i.putExtra("kursus", arrKursus[p]);
startActivity(i);
}
});
}
}

Load image dari drawable String


private void showImage() {
String uri = "drawable/icon";
// int imageResource = R.drawable.icon;
int imageResource = getResources().getIdentifier(uri, null,
getPackageName());
ImageView imageView = (ImageView)
findViewById(R.id.myImageView);
Drawable image = getResources().getDrawable(imageResource);
imageView.setImageDrawable(image);
}

Dial:
String toDial="tel:"+number.getText().toString();
startActivity(new Intent(Intent.ACTION_DIAL,Uri.parse(toDial)));

PROPERTIES

android:typeface="sans"
android:textColor="#ff00ff33"
inputType =phone
inputType =text
<EditText android:inputType="text|textEmailAddress"/>
<EditText android:inputType="number|numberSigned|numberDecimal"/>
<EditText android:inputType="date"/>
<EditText android:inputType="text|textMultiLine|textAutoCorrect"
android:minLines="3" android:gravity="top"/>
<DatePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TimePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<activity

android:theme="@android:style/Theme.Dialog"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"

http://maps.google.com/maps?saddr=6.358464,106.829481&daddr=6.316834,106.837378+to:6.331337,106.834459+to:6.326218,106.809912+to:6.303184,106.839609
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ScrollView
android:layout_marginBottom="50dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#999999"
>
<TableLayout>
<TableRow>
<TextView android:text="Selamat Datang" />
</TableRow>
<TableRow >
<ImageView android:id="@+id/myGambar"
android:src="@drawable/info"/>
</TableRow>
<TableRow android:id="@+id/TableRow00"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txtPesan"
android:layout_marginTop="51dp"
android:text="PlaySong" />
</TableRow>
<TableRow android:id="@+id/TableRow00"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="@+id/edKonversi"
android:layout_height="wrap_content"
android:text="100"
android:layout_width="wrap_content">
</EditText>
</TableRow>
<TableRow android:id="@+id/TableRow00"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/txtHasil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"

android:text="Hasil Konversi" />


</TableRow>
<TableRow android:id="@+id/TableRow02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/mainMarquee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="selamat datang di aplikasi android "
android:textSize="14sp"
android:layout_x="3px"
android:layout_y="4px"
android:typeface="sans"
android:textColor="#0000ff"
android:background="#000000"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever">
</TextView>
</TableRow>
</TableLayout>
</ScrollView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="50dip"
>
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1"
>
<TableRow android:id="@+id/TableRowmarquee"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/mainMarquee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="selamat datang di aplikasi android "
android:textSize="14sp"
android:layout_x="3px"
android:layout_y="4px"
android:typeface="sans"
android:textColor="#0000ff"
android:background="#000000"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever">
</TextView>
</TableRow>
<TextView
android:id="@+id/txtwellcome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:text="Silakan isi form registrasi :"

android:textAppearance="?android:attr/textAppearanceLarge" />
<TableRow>
<TextView android:text="Nama:" />
<EditText android:id="@+id/lnama" />
</TableRow>
<TableRow>
<TextView android:text="Tmp lahir:" />
<AutoCompleteTextView android:id="@+id/ltlahir" />
</TableRow>
<TableRow>
<TextView android:text="Tgl Lahir:" />
<DatePicker
android:id="@+id/dpTglLahir"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView android:text="Jenis_Kelamin:" />
<RadioGroup
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="@+id/radPa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Laki-laki"
android:checked="true" />
<RadioButton android:id="@+id/radPi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Perempuan" />
</RadioGroup>
</TableRow>
<TableRow>
<TextView android:text="Telepon:" />
<EditText android:id="@+id/ltelp" android:inputType ="phone" />
</TableRow>
<TableRow>
<TextView android:text="Agama:" />
<Spinner
android:id="@+id/spinAgama"
android:drawSelectorOnTop="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow>
<TextView android:text="Status:" />
<CheckBox android:id="@+id/chkStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sudah Bekerja" />
</TableRow>
<TableRow>
<TextView android:text="Alamat" />
<EditText android:id="@+id/lalamat"
android:singleLine="false"
android:gravity="top"
android:lines="2"
android:scrollHorizontally="false"
android:maxLines="2"
android:maxWidth="200sp"
/>
</TableRow>

<ImageView
android:id="@+id/pilGambar"
android:layout_width="wrap_content"
android:layout_height="140dp"
android:background="@drawable/user"
android:padding="10dp" />
<TableRow>
<Button android:id="@+id/btnClear"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Clear"
android:visibility="visible"
/>
<Button android:id="@+id/btnSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save"
/>
</TableRow>
</TableLayout>
</ScrollView>

Detail.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ScrollView
android:layout_marginBottom="50dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#999999"
>
<TableLayout android:id="@+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#fff">
<TextView
android:id="@+id/txtMarquee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="14sp"
android:layout_x="3px"
android:layout_y="4px"
android:typeface="sans"
android:textColor="#0000ff"
android:background="#000000"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever">
</TextView>
<ImageView
android:id="@+id/myGambar"
android:layout_centerHorizontal="true"
android:src="@drawable/gunung"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

/>
<TableRow android:id="@+id/TableRow00"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Kode Wisata:" />
<TextView android:id="@+id/ikode_wisata" />
</TableRow>
<TableRow android:id="@+id/TableRow10"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Nama Wisata:" />
<TextView android:id="@+id/inama_wisata" />
</TableRow>
<TableRow android:id="@+id/TableRow01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Alamat :"/>
<TextView android:id="@+id/ialamat" />
</TableRow>
<TableRow android:id="@+id/TableRow02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Jarak :"/>
<TextView android:id="@+id/ijarak" />
</TableRow>
<TableRow android:id="@+id/TableRow03"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Koordinat :"/>
<TextView android:id="@+id/ikoordinat" />
</TableRow>
<TableRow android:id="@+id/TableRow04"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Fasilitas :"/>
<TextView android:id="@+id/iketerangan" />
</TableRow>
<TableRow android:id="@+id/TableRow05"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Catatan :"/>
<TextView android:id="@+id/ideskripsi" />
</TableRow>
<TableRow android:id="@+id/TableRow06"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Posisi Anda :"/>
<TextView android:id="@+id/iposanda" />
</TableRow>
<TableRow android:id="@+id/TableRow06"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button android:id="@+id/btnDirection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Go Direction"
android:visibility="visible"
/>
</TableRow>
</TableLayout>
</ScrollView>

</RelativeLayout>
Detail.java
import
import
import
import
import
import
import
import

android.os.Bundle;
android.app.Activity;
android.content.Intent;
android.view.Menu;
android.view.View;
android.widget.Button;
android.widget.ImageView;
android.widget.TextView;

public class detail extends Activity {


String mylati="6.173174";
String mylongi="106.825476";
String myposisi="Kampus Universitas Gunadarma Kelapa Dua";
String
kode_wisata,nama_wisata,alamat,latitude,longitude,jarak,gambar,keterangan,
deskripsi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
Intent io = this.getIntent();
kode_wisata=io.getStringExtra("kode_wisata");
nama_wisata=io.getStringExtra("nama_wisata");
alamat=io.getStringExtra("alamat");
latitude=io.getStringExtra("latitude");
longitude=io.getStringExtra("longitude");
jarak=io.getStringExtra("jarak");
gambar=io.getStringExtra("gambar");
keterangan=io.getStringExtra("keterangan");
deskripsi=io.getStringExtra("deskripsi");
mylati=io.getStringExtra("mylati");
mylongi=io.getStringExtra("mylongi");
myposisi=io.getStringExtra("myposisi");
TextView
TextView
TextView
TextView
TextView
TextView
TextView
TextView

txtKode=(TextView)findViewById(R.id.ikode_wisata);
txtNama=(TextView)findViewById(R.id.inama_wisata);
txtAlamat=(TextView)findViewById(R.id.ialamat);
txtKoordinat=(TextView)findViewById(R.id.ikoordinat);
txtJarak=(TextView)findViewById(R.id.ijarak);
txtKet=(TextView)findViewById(R.id.iketerangan);
txtDes=(TextView)findViewById(R.id.ideskripsi);
txtPos=(TextView)findViewById(R.id.iposanda);

txtKode.setText(kode_wisata);
txtNama.setText(nama_wisata);
txtJarak.setText(jarak+" Km");
txtAlamat.setText(alamat);
txtKoordinat.setText(latitude+","+longitude);
txtKet.setText(keterangan);
txtDes.setText(deskripsi);
txtPos.setText(myposisi+" ("+mylati+","+mylongi+")");
Button btnmap=(Button)findViewById(R.id.btnDirection);
btnmap.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i= new Intent(detail.this, map.class);
startActivity(i);

}});
}
}
Inputnama.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ScrollView
android:layout_marginBottom="50dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#999999"
>
<TableLayout android:id="@+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#fff">
<TextView
android:id="@+id/txtMarquee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="14sp"
android:layout_x="3px"
android:layout_y="4px"
android:typeface="sans"
android:textColor="#0000ff"
android:background="#000000"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever">
</TextView>
<ImageView
android:id="@+id/myGambar"
android:layout_centerHorizontal="true"
android:src="@drawable/user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TableRow android:id="@+id/TableRow00"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Nama " />
<EditText android:id="@+id/inama" />
</TableRow>
<TableRow android:id="@+id/TableRow01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Usia "/>
<EditText android:id="@+id/iusia" android:inputType="number|
numberSigned|numberDecimal" />
</TableRow>
<TableRow android:id="@+id/TableRow02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Jenis Kelamin"/>
<RadioGroup

android:id="@+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton android:text="Laki-laki"
android:id="@+id/radPa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:textColor="#000">
</RadioButton>
<RadioButton android:text="Perempuan"
android:id="@+id/radPi"
android:layout_width="wrap_content"
android:textColor="#000"
android:layout_height="wrap_content">
</RadioButton>
</RadioGroup>
</TableRow>
<TableRow android:id="@+id/TableRow02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button android:id="@+id/iBatal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Batal"
/>
<Button android:id="@+id/iOk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="OK"
android:visibility="visible"
/>
</TableRow>
</TableLayout>
</ScrollView>
</RelativeLayout>

Inputnama.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ScrollView
android:layout_marginBottom="50dip"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#999999"
>
<TableLayout android:id="@+id/TableLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#fff">
<TextView
android:id="@+id/txtMarquee"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="14sp"
android:layout_x="3px"

android:layout_y="4px"
android:typeface="sans"
android:textColor="#0000ff"
android:background="#000000"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever">
</TextView>

<ImageView
android:id="@+id/myGambar"
android:layout_centerHorizontal="true"
android:src="@drawable/user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

<TableRow android:id="@+id/TableRow00"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Nama " />
<EditText android:id="@+id/inama" />
</TableRow>
<TableRow android:id="@+id/TableRow01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Usia "/>
<EditText android:id="@+id/iusia" android:inputType="number|
numberSigned|numberDecimal" />
</TableRow>
<TableRow android:id="@+id/TableRow02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:text="Jenis Kelamin"/>
<RadioGroup
android:id="@+id/RadioGroup01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton android:text="Laki-laki"
android:id="@+id/radPa"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:textColor="#000">
</RadioButton>
<RadioButton android:text="Perempuan"
android:id="@+id/radPi"
android:layout_width="wrap_content"
android:textColor="#000"
android:layout_height="wrap_content">
</RadioButton>
</RadioGroup>
</TableRow>
<TableRow android:id="@+id/TableRow02"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button android:id="@+id/iBatal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Batal"
/>
<Button android:id="@+id/iOk"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:text="OK"
android:visibility="visible"
/>
</TableRow>
</TableLayout>
</ScrollView>
</RelativeLayout>
Inputnama.java

import java.util.Calendar;
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import
import

android.os.Bundle;
android.app.Activity;
android.app.AlertDialog;
android.content.DialogInterface;
android.content.Intent;
android.content.DialogInterface.OnClickListener;
android.text.Html;
android.text.TextUtils;
android.view.KeyEvent;
android.view.Menu;
android.view.MenuItem;
android.view.SubMenu;
android.view.View;
android.webkit.WebSettings;
android.webkit.WebView;
android.webkit.WebViewClient;
android.widget.Button;
android.widget.EditText;
android.widget.RadioButton;
android.widget.TextView;
android.widget.Toast;

public class inputnama extends Activity {


EditText txtnama,txtusia;
RadioButton radPa,radPi;
String jk="Laki-laki";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inputnama);
callMarquee();
txtnama= (EditText) findViewById(R.id.inama);
txtusia= (EditText) findViewById(R.id.iusia);
radPa= (RadioButton) findViewById(R.id.radPa);
radPa.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
jk="Laki-laki";
}
});
radPi= (RadioButton) findViewById(R.id.radPi);

radPi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
jk="Perempuan";
}
});
Button btnOk= (Button) findViewById(R.id.iOk);
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nama=txtnama.getText().toString();
String usia=txtusia.getText().toString();
if(nama.length()<1){lengkapi("Nama");}
else if(usia.length()<1){lengkapi("Usia");}
else{
Intent put= new Intent(getBaseContext(),
soalsoal.class);
put.putExtra("nama", nama);
put.putExtra("usia", usia);
put.putExtra("jk", jk);
startActivity(put);
}
}
});
Button btnBatal= (Button) findViewById(R.id.iBatal);
btnBatal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
keluar();
}
});
}
public void lengkapi(String item){
new AlertDialog.Builder(this)
.setTitle("Lengkapi Data")
.setMessage("Silakan lengkapi data "+item)
.setNeutralButton("OK", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin)
{
}})
.show();
}
public void keluar(){
new AlertDialog.Builder(this)
.setTitle("Menutup Aplikasi")
.setMessage("Terimakasih... Anda Telah Menggunakan
Aplikasi Ini")
.setNeutralButton("Tutup", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin)
{

finish();
}})
.show();
}
public void keluarYN(){
AlertDialog.Builder ad=new AlertDialog.Builder(inputnama.this);
ad.setTitle("Konfirmasi");
ad.setMessage("Apakah benar ingin keluar?");
ad.setPositiveButton("OK",new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int
which) {
keluar();
}});
ad.setNegativeButton("No",new OnClickListener(){
public void onClick(DialogInterface arg0, int arg1) {
}});
ad.show();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
keluarYN();
return true;
}
return super.onKeyDown(keyCode, event);
}
void callMarquee(){
Calendar cal = Calendar.getInstance();
int jam = cal.get(Calendar.HOUR);
int menit= cal.get(Calendar.MINUTE);
int detik= cal.get(Calendar.SECOND);
int tgl= cal.get(Calendar.DATE);
int bln= cal.get(Calendar.MONTH);
int thn= cal.get(Calendar.YEAR);
String stgl=String.valueOf(tgl)+"-"+String.valueOf(bln)
+"-"+String.valueOf(thn);
String sjam=String.valueOf(jam)+":"+String.valueOf(menit)
+":"+String.valueOf(detik);
TextView txtMarquee=(TextView)findViewById(R.id.txtMarquee);
txtMarquee.setSelected(true);
String kata="Selamat Datang di Aplikasi Android ..Selamat
Mengerjakan /"+stgl+"/"+sjam+" #";
String kalimat=String.format("%1$s",TextUtils.htmlEncode(kata));
txtMarquee.setText(Html.fromHtml(kalimat+kalimat+kalimat));
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 1, 0, "Arsip").setIcon(R.drawable.keluar);
return true;
}

public boolean onOptionsItemSelected(MenuItem item) {


switch (item.getItemId()) {
case 1:
Intent put= new Intent(getBaseContext(), listdataDB.class);
startActivity(put);
return true;
}
return false;
}
}

https://code.google.com/apis/console/
MainActivity.java
package com.lp2maray.ui;
import
import
import
import
import

com.google.android.gms.maps.CameraUpdateFactory;
com.google.android.gms.maps.GoogleMap;
com.google.android.gms.maps.SupportMapFragment;
com.google.android.gms.maps.model.LatLng;
com.google.android.gms.maps.model.MarkerOptions;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity{

private GoogleMap map;


@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupMap();
}
private void setupMap(){
if (map == null){
map = ((SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.maps)).getMap();
if (map != null){
map.addMarker(new MarkerOptions().position(new LatLng(-6.353868,
106.832845)).title("lp2m aray")
.snippet(Halte Kampus UI Depok)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));

map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-6.353868,
106.832845),10));
}
}
}
}
-------------------------------------------------------------<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
<fragment
android:id="@+id/maps"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
---------------------------------------<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lp2maray.ui"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" />
<permission
android:name="com.example.tesmap.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.tesmap.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<!-- Google Maps API V2 -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyBB4xNonnjwaYlVWjofX1heCuJ97I3IsNA" />

<activity
android:name="com.example.tesmap.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
public static void BubbleSort(){
int j;
boolean flag = true; // set flag to true to begin first pass
double temp=0.0; //holding variable
String stemp="";
while ( flag ){
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < jd -1; j++ ){
if ( dJarak[ j ] > dJarak[j+1] ) {
temp = dJarak[ j ];
dJarak[ j ] = dJarak[ j+1 ];
dJarak[ j+1 ] = temp;
stemp=arNama[j];
arNama[ j ] = arNama[ j+1 ];
arNama[ j+1 ] = stemp;
flag = true;
}

}
================================================================
==============================

LOAD URL IMAGE

new DownloadImageTask((ImageView)
findViewById(R.id.dlGambar)).execute(arUrlFoto);
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
}
catch (Exception e) {Log.e("Error", e.getMessage());e.printStackTrace();}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {bmImage.setImageBitmap(result); }
}
================================================================
=====
public static double hitJarak(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = 3958.75;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);

double a = Math.sin(dLat/2) * Math.sin(dLat/2) +


Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
int meterConversion = 1609;
double myjr=dist * meterConversion;
return Math.floor(myjr/1000);
}
ImageView k1 = (ImageView) this.findViewById(R.id.cmdCari);
k1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
String kata=txtCari.getText().toString();
String alamat="";
try {
alamat="http://translate.google.com.tw/translate_a/t?
client=t&hl=en&sl=id&tl=fr&ie=UTF-8&oe=UTF-8&multires=1&oc=1&otf=2&ssel=0&tsel=0&sc=1&q="
+ URLEncoder.encode(kata, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

}
}

XMLParser parser = new XMLParser();


String xml=null;
try {
xml = parser.getXmlFromUrl(alamat);
String kal=translate(xml);
txtHasil.setText(kal);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtHasil.setText("err data ");
}

});

String translate(String result){


result = result.substring(2, result.indexOf("]]") + 1);
StringBuilder sb = new StringBuilder();
String[] splits = result.split("(?<!\\\\)\"");
for(int i = 1; i < splits.length; i += 8)
sb.append(splits[i]);
return sb.toString().replace("\\n", "\n").replaceAll("\\\\(.)", "$1");
}

Button btnProses=(Button)findViewById(R.id.button1);
btnProses.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
myip=txtIp.getText().toString();
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}});
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
try{
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
qr=contents;
XMLParser parser = new XMLParser();
String xml=null;
URL = myip+"/simonas/posisi.php?tn="+qr+"&ket=ok";
//Toast.makeText(menu.this,"URL:"+URL, Toast.LENGTH_LONG).show();
xml = parser.getXmlFromUrl(URL);
if(xml.indexOf("Tiket")>=0){ pesan(xml); }
}

else if (resultCode == RESULT_CANCELED) {qr="";


}
catch(Exception ee){ qr="";salah();}
}

batal();}

}
map.addMarker(new MarkerOptions().position(new LatLng(alat, alon)).title("Posisi
Anda").snippet(myCity).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
String in(String p,String k){
String l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghipqrstuvwxyz0123456789!@#&%*()-_=:,.'?/$^ ";
int pms=l.length();
int pln=p.length();
int ky=k.length();
String y =k;
int m = pln%ky;
for( int i=1; i<pln/ky ; i++){k=k+y;}
k=k+k.substring(0,m);
System.out.println("Key2 Text:\t"+k);
System.out.println("=============================================");
String c="";
for (int j=0; j<pln; j++ ){
char hsl=l.charAt((l.indexOf(k.charAt(j)) + l.indexOf(p.charAt(j)))%pms);
c=c + l.charAt((l.indexOf(k.charAt(j)) + l.indexOf(p.charAt(j)))%pms);
}
return c;
}
//===============================================================
===================
String out(String p,String k){
String l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#&%*()-_=:,.'?/$^
";
int pms=l.length();
int cpr=p.length();
int ky=k.length();
String y =k;
int m = cpr%ky;
for( int i=1; i<cpr/ky ; i++){k=k+y;}
k=k+k.substring(0,m);
String pl = "";
for (int j=0; j<cpr; j++ ){
char hsl=l.charAt(((l.indexOf(p.charAt(j)) - l.indexOf(k.charAt(j))) +pms )%pms);
pl=pl + hsl;
}
return pl;
}

try {
//set the download URL, a url that points to a file on the internet
//this is the file to be downloaded
URL url = new URL("http://somewhere.com/some/webhosted/file");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = Environment.getExternalStorageDirectory();
//create a new file, specifying the path, and the filename
//which we want to save the file as.

File file = new File(SDCardRoot,"somefile.ext");


//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
//add the data in the buffer to the file in the file output stream (the
file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
//this is where you would do something to report the prgress, like this
maybe
updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
//catch some possible errors...
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

===============
Start Email-Activity with Preset Data (via Intents)
3 votes 7 comments

This code starts the email activity with pre-set data. On the emulator it might get a "No application can perform
this action" failure, although it works on a real phone. Code picked up on anddev
raw
copy
download
/* Create the Intent */
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
/* Fill it with Data */
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"to@email.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Text");
/* Send it off to the Activity-Chooser */
context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));

Display a progress dialog while computing


2 votes 3 comments

This snippet creates a ProgressDialog and a thread to execute something with an unknown duration (web
service as an example). When this "thing" finishes, a message is sent to the parent of the thread to stop the
ProgessDialog.
raw
copy
download

final ProgressDialog dialog = ProgressDialog.show(this, "Title", "Message", true);


final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
public void run() {
//
// YOUR LONG CALCULATION (OR OTHER) GOES HERE
//
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();

Prompt User Input with an AlertDialog


6 votes 16 comments

This code creates an input-dialog with AlertDialog.Builder where a user can enter text in an EditText field and
press on "Ok" and "Cancel".
raw
copy
download
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();

Send a notification
1 vote 1 comment

Useful for your threads, as they can't access the display interface.
raw
copy
download
protected void sendnotification (String title, String message) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
int icon = R.drawable.icon;
CharSequence tickerText = message;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = title;
CharSequence contentText = message;
Intent notificationIntent = new Intent(this, AndroToDo.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
0);

notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, notification);

Latitude and Longitude of a place


1 vote 0 comments

One can know the latitude and longitude of a place if know the place name.
raw
copy
download
//---geo-coding--Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
empire state building, 5);
String add = ;
if (addresses.size() > 0) {
p = new GeoPoint(
(int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
mc.animateTo(p);
mapView.invalidate();
}
} catch (IOException e) {
e.printStackTrace();
}

Post a tweet on Twitter


3 votes 5 comments

This code authenticates and posts a tweet on Twitter. Written by Davanum Srinivas
raw
copy
download
package org.apache.twitter;
import
import
import
import
import
import
import
import
import
import

android.app.Activity;
android.content.Intent;
android.net.http.RequestQueue;
android.os.Bundle;
android.util.Log;
android.view.View;
android.webkit.WebView;
android.widget.Button;
android.widget.EditText;
org.apache.commons.codec.binary.Base64;

import
import
import
import
import

java.io.ByteArrayInputStream;
java.io.UnsupportedEncodingException;
java.net.URLEncoder;
java.util.HashMap;
java.util.Map;

/**
* Initial screen with edit box for tweets and
* a web view to display the tweets from friends
*/
public class TwitterClient extends Activity {
static final int GET_LOGIN_INFORMATION = 1;
WebView webView;
RequestQueue requestQueue;
String authInfo;
/**
* Called with the activity is first created.
*/
@Override
public void onCreate(Bundle icicle) {

super.onCreate(icicle);
setContentView(R.layout.main);
// Set the initial text
webView = (WebView) findViewById(R.id.webView);
webView.loadData(
"Please click on setup and enter your twitter credentials",
"text/html", "utf-8");
// When they click on the set up button show the login screen
Button button = (Button) findViewById(R.id.setup);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(TwitterClient.this, TwitterLogin.class);
startSubActivity(intent, GET_LOGIN_INFORMATION);
}
});
// When they click on the Tweet! button, then get the
// text in the edit box and send it to twitter
final Activity activity = this;
Button button2 = (Button) findViewById(R.id.update);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("http", "Update clicked");
Map headers = new HashMap();
if (authInfo == null) {
return;
}
headers.put("Authorization", "Basic " + new
String(Base64.encodeBase64(authInfo.getBytes())));
EditText user = (EditText) findViewById(R.id.updateText);
String text = null;
try {
text = "status=" + URLEncoder.encode(user.getText().toString(), "UTF8");
Log.i("http", "with " + text);
} catch (UnsupportedEncodingException e) {
Log.e("http", e.getMessage());
}
byte[] bytes = text.getBytes();
ByteArrayInputStream baos = new ByteArrayInputStream(bytes);
// See Twitter API documentation for more information
// http://groups.google.com/group/twitter-development-talk/web/apidocumentation
requestQueue.queueRequest(
"https://twitter.com/statuses/update.xml",
"POST", headers, new MyEventHandler2(activity), baos,
bytes.length, false);
}
});
// Start a thread to update the tweets from friends every minute
requestQueue = new RequestQueue(this);
Thread t = new Thread(new MyRunnable(this));
t.start();
}
protected void onActivityResult(int requestCode, int resultCode,
String data, Bundle extras) {
if (requestCode == GET_LOGIN_INFORMATION && resultCode == RESULT_OK) {
// Save the user login information
authInfo = data;
}
}
}

Network connectivity changes


1 vote 0 comments

This snippets configures listening for connectivity events (wifi, 3g) on and off
raw
copy
download

//put this in your activity, service, or whatever


private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isWifiConnected = false;
boolean isMobileConnected = false;
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(networkInfo != null)
isWifiConnected = networkInfo.isConnected();
networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(networkInfo != null)
isMobileConnected = networkInfo.isConnected();
Log.d("network status", "wifi == " + isWifiConnected + " and mobile == " +
isMobileConnected);
};

//registering the receiver from activity, service


registerReceiver(mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
//or
context.registerReceiver(mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); //where context
it's a Context class object
//manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Basic service example in android


2 votes 0 comments

Service -A Service is an application component representing either an application's desire to perform a longerrunning operation while not interacting with the user or to supply functionality for other applications to use.
Difference between a Thread , service and asynchronous task
1) Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you
won't create a blank activity for it, for this you will use a Service.
2) A Thread is a Thread, probably you already know it from other part. You need to know that you cannot
update UI from a Thread. You need to use a Handler for this, but read further.
3) An AsyncTask is an intelligent Thread that is advised to be used. Intelligent as it can help with it's methods,
and there are two methods that run on UI thread, which is good to update UI components
Continue Reading
raw
copy
download
public class ServiceDemoActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.start).setOnClickListener(this);
findViewById(R.id.stop).setOnClickListener(this);
}
private Intent inetnt;
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
inetnt=new Intent(this,ServiceExample.class);
startService(inetnt);
break;
case R.id.stop:
inetnt=new Intent(this,ServiceExample.class);
stopService(inetnt);
break;
}

@Override
protected void onResume() {
super.onResume();
}

//
}

@Override
protected void onDestroy() {
super.onDestroy();
}

Using C-style printf format strings to include variables in strings.xml


2 votes 0 comments

Variables can be included in the strings defined in strings.xml using the C-style printf '%' syntax. This is
because getString passes the string through java.util.Formatter.
In the example above, getString substitutes %d for the integer 10 in the string message.
This tip was taken from Bram Borggreve's blog ( bVirtual.nl ).
raw
copy
download
// In strings.xml
<string name="unread_messages">You have %d unread messages</string>
// In Java code
String message = getString(R.string.unread_messages, 10);

Kill You Application


5 votes 5 comments

If you want to completely kill your application, rather than just finish the activity then either of the above
snippets will do.
Thanks to sammyF on #android for the second way, which is shorter but probably less of an official way to do
it.
raw
copy
download
/* Way one */
android.os.Process.killProcess(android.os.Process.myPid())

/* Way Two */
System.exit(0);

Check if SD card is present


2 votes 0 comments

Sometimes we need to know whether an SD card is present or not. So here is a check to see if an SD card is
present. It returns true if the SD card is present and writable, false otherwise. first posted on anddev by
MrSnowflake
raw
copy
download
public static boolean isSdPresent() {
return
android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNT
ED);
}

Webview load from assets


1 vote 0 comments

Load your website from assets folder and display it in WebView


raw
copy
download
public class ViewWeb extends Activity {
WebView webview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webview = (WebView) findViewById(R.id.webView1);
webview.loadUrl("file:///android_asset/index.html");
}
}

Get installed Applications with Name, Package Name, Version and Icon
9 votes 10 comments

This helper function retrieves all installed apps with the application name, package name, version-number and
-code as well as the icons. The method getPackages() returns an ArrayList with all the apps.
raw
copy
download
class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private Drawable icon;
private void prettyPrint() {
Log.v(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
}
}
private ArrayList<PInfo> getPackages() {
ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i<max; i++) {
apps.get(i).prettyPrint();
}
return apps;
}
private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i<packs.size();i++) {

PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);

}
return res;

Open URL in android


1 vote 0 comments

To open the url in android


raw
copy
download
String url = "url";
Intent intent1 = new Intent(Intent.ACTION_VIEW);
intent1.setData(Uri.parse(url));
startActivity(intent1);

Non-Blocking Web-Request
8 votes 11 comments

This code fetches content from the web without blocking the UI (runs in the background in a Thread). Once
finished, it posts a Handler that is picked up by the UI as soon as possible.
raw
copy
download
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
public class Iconic extends Activity {
private String html = "";
private Handler mHandler;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler = new Handler();
checkUpdate.start();
}
private Thread checkUpdate = new Thread() {
public void run() {
try {
URL updateURL = new URL("http://iconic.4feets.com/update");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}

/* Convert the Bytes read to a String. */


html = new String(baf.toByteArray());
mHandler.post(showUpdate);
} catch (Exception e) {
}

};

private Runnable showUpdate = new Runnable(){


public void run(){
Toast.makeText(Iconic.this, "HTML Code: " + html, Toast.LENGTH_SHORT).show();
}
};

Check for Updates Once a Day


5 votes 19 comments

This code checks for updates of the Activity once a day and in the background. If an update (higher version than
current) is found, it opens a Dialog and asks the user to open the market.
raw
copy
download
public class Test extends Activity {
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.front);
mHandler = new Handler();
/* Get Last Update Time from Preferences */
SharedPreferences prefs = getPreferences(0);
lastUpdateTime = prefs.getLong("lastUpdateTime", 0);
/* Should Activity Check for Updates Now? */
if ((lastUpdateTime + (24 * 60 * 60 * 1000)) < System.currentTimeMillis()) {
/* Save current timestamp for next Check*/
lastUpdateTime = System.currentTimeMillis();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();
/* Start Update */
checkUpdate.start();
}

/* This Thread checks for Updates in the Background */


private Thread checkUpdate = new Thread() {
public void run() {
try {
URL updateURL = new URL("http://my.company.com/update");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
/* Convert the Bytes read to a String. */
final String s = new String(baf.toByteArray());

0).versionCode;

/* Get current Version Number */


int curVersion = getPackageManager().getPackageInfo("your.app.id",
int newVersion = Integer.valueOf(s);

/* Is a higher version than the current already out? */


if (newVersion > curVersion) {
/* Post a Handler for the UI to pick up and open the Dialog */
mHandler.post(showUpdate);
}
} catch (Exception e) {
}

};

/* This Runnable creates a Dialog and asks the user to open the Market */
private Runnable showUpdate = new Runnable(){
public void run(){
new AlertDialog.Builder(Test.this)
.setIcon(R.drawable.icon)
.setTitle("Update Available")
.setMessage("An update for is available!\\n\\nOpen Android Market and see the
details?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://search?q=pname:your.app.id"));
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Cancel */
}
})
.show();
}
};
}

Gallery widget with remote Images


1 vote 3 comments

This code-snippet loads the Gallery widget with remote images from a webserver. Found on anddev
raw
copy
download
/** == XML Layout ==
*
* <?xml version="1.0" encoding="utf-8"?>
* <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
*
android:orientation="vertical"
*
android:layout_width="fill_parent"
*
android:layout_height="fill_parent"
*
>
* <Gallery id="@+id/gallery"
*
android:layout_width="fill_parent"
*
android:layout_height="wrap_content"
*
android:gravity="bottom"
* />
* </LinearLayout>
*
*/
package org.anddev.android.galleryexample;
import
import
import
import
import

java.io.BufferedInputStream;
java.io.IOException;
java.io.InputStream;
java.net.URL;
java.net.URLConnection;

import
import
import
import
import
import
import
import
import
import
import

android.app.Activity;
android.content.Context;
android.graphics.Bitmap;
android.graphics.BitmapFactory;
android.os.Bundle;
android.util.Log;
android.view.View;
android.view.ViewGroup;
android.widget.BaseAdapter;
android.widget.Gallery;
android.widget.ImageView;

public class GalleryExample extends Activity {


/** Called when the activity is first created. */

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

/* Find the gallery defined in the main.xml


* Apply a new (custom) ImageAdapter to it. */
((Gallery) findViewById(R.id.gallery))
.setAdapter(new ImageAdapter(this));

public class ImageAdapter extends BaseAdapter {


/** The parent context */
private Context myContext;
/** URL-Strings to some remote images. */
private String[] myRemoteImages = {
"http://www.anddev.org/images/tiny_tutheaders/weather_forecast.png",
"http://www.anddev.org/images/tiny_tutheaders/cellidtogeo.png",
"http://www.anddev.org/images/tiny_tutheaders/droiddraw.png"
};
/** Simple Constructor saving the 'parent' context. */
public ImageAdapter(Context c) { this.myContext = c; }
/** Returns the amount of images we have defined. */
public int getCount() { return this.myRemoteImages.length; }
/* Use the array-Positions as unique IDs */
public Object getItem(int position) { return position; }
public long getItemId(int position) { return position; }
/** Returns a new ImageView to
* be displayed, depending on
* the position passed. */
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(this.myContext);
try {

/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(myRemoteImages[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
/* Apply the Bitmap to the ImageView that will be returned. */
i.setImageBitmap(bm);
} catch (IOException e) {
i.setImageResource(R.drawable.error);
Log.e("DEBUGTAG", "Remtoe Image Exception", e);
}

/* Image should be scaled as width/height are set. */


i.setScaleType(ImageView.ScaleType.FIT_CENTER);
/* Set the Width/Height of the ImageView. */
i.setLayoutParams(new Gallery.LayoutParams(150, 150));
return i;
}
/** Returns the size (0.0f to 1.0f) of the views
* depending on the 'offset' to the center. */
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float)Math.pow(2, Math.abs(offset)));
}
}

Enable and Disable WiFi


2 votes 0 comments

The WifiManager can be used to enable and disable wifi. Where 'enabled' is a boolean. Found on
damonkohler.com
raw
copy
download
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(enabled);

Network connectivity changes


1 vote 0 comments

This snippets configures listening for connectivity events (wifi, 3g) on and off
raw
copy
download
//put this in your activity, service, or whatever
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isWifiConnected = false;
boolean isMobileConnected = false;
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(networkInfo != null)
isWifiConnected = networkInfo.isConnected();
networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(networkInfo != null)
isMobileConnected = networkInfo.isConnected();
Log.d("network status", "wifi == " + isWifiConnected + " and mobile == " +
isMobileConnected);
};

//registering the receiver from activity, service


registerReceiver(mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
//or
context.registerReceiver(mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); //where context
it's a Context class object
//manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Sending SMS with SmsManager


1 vote 0 comments

It's easy to send SMS Messages using the SmsManager


raw
copy
download
SmsManager m = SmsManager.getDefault();
String destination = "06761122334";

String text = "Hello, Jenny!";


m.sendTextMessage(destination, null, text, null, null);

Scan for Wireless Networks


1 vote 2 comments

Scan for wireless networks in the current area. first posted on anddev by nas061000
raw
copy
download
package com.android.wifitester;
import
import
import
import
import
import
import
import
import
import
import
import

java.util.List;
android.app.Activity;
android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
android.content.IntentFilter;
android.net.wifi.ScanResult;
android.net.wifi.WifiManager;
android.os.Bundle;
android.view.Menu;
android.view.MenuItem;
android.widget.TextView;

public class WifiTester extends Activity {


TextView mainText;
WifiManager mainWifi;
WifiReceiver receiverWifi;
List<ScanResult> wifiList;
StringBuilder sb = new StringBuilder();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainText = (TextView) findViewById(R.id.mainText);
mainWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
receiverWifi = new WifiReceiver();
registerReceiver(receiverWifi, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mainWifi.startScan();
mainText.setText("\\nStarting Scan...\\n");
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, "Refresh");
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
mainWifi.startScan();
mainText.setText("Starting Scan");
return super.onMenuItemSelected(featureId, item);
}
protected void onPause() {
unregisterReceiver(receiverWifi);
super.onPause();
}
protected void onResume() {
registerReceiver(receiverWifi, new
IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
sb = new StringBuilder();
wifiList = mainWifi.getScanResults();
for(int i = 0; i < wifiList.size(); i++){
sb.append(new Integer(i+1).toString() + ".");
sb.append((wifiList.get(i)).toString());
sb.append("\\n");
}

}
}

mainText.setText(sb);

Method for enable disable wifi


1 vote 0 comments

Enable disable wifi with this method ;)


Add permission ;)
raw
copy
download
public boolean enableWIFI()
{
WifiManager wifiManager = (WifiManager)
this.getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled()){
if(wifiManager.setWifiEnabled(false))
return true;
}else{
if(wifiManager.setWifiEnabled(true))
return true;
}
return false;
}

Get My Phone Number


2 votes 3 comments

Gets the phone number the app is running on. It needs a permission so add the line uses-permission
android:name="android.permission.READ_PHONE_STATE" to the manifest.xml
raw
copy
download
private String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
private String getMy10DigitPhoneNumber(){
String s = getMyPhoneNumber();
return s.substring(2);
}

Change phone mode to silent, vibrate, normal


2 votes 1 comment

This code will allow you to change your phone modes accordingly.
raw
copy
download
AudioManager am;
am= (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);
//For Normal mode
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
//For Silent mode
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
//For Vibrate mode
am.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

Open Wifi Settings

3 votes 1 comment

Open wifi settings :)


raw
copy
download
null);

final Intent intent = new Intent(Intent.ACTION_MAIN,

intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new
ComponentName("com.android.settings", "com.android.settings.wifi.WifiSettings");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity( intent);

Enable and Disable WiFi


2 votes 0 comments

The WifiManager can be used to enable and disable wifi. Where 'enabled' is a boolean. Found on
damonkohler.com
raw
copy
download
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(enabled);

Open mobile data setting


1 vote 0 comments

Open mobile data settings


raw
copy
download
final Intent intent=new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new
ComponentName("com.android.phone","com.android.phone.Settings");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

Check airplane mode and roaming in current moment


2 votes 0 comments

Check airplane mode and roaming in current moment.


raw
copy
download
// Get roaming state from telephony manager
public Boolean isRoaming(Context context) {
TelephonyManager telephonyManager =
(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
return telephonyManager.isNetworkRoaming();
}
// Get airplane mode state from system settings
public boolean isAirplaneMode(Context context) {
int settingValue;
try {
settingValue = Settings.System.getInt(
context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON);
return settingValue != 0;
} catch (SettingNotFoundException e) {
return false;
}
}

Check for Updates Once a Day

5 votes 19 comments

This code checks for updates of the Activity once a day and in the background. If an update (higher version than
current) is found, it opens a Dialog and asks the user to open the market.
raw
copy
download
public class Test extends Activity {
private Handler mHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.front);
mHandler = new Handler();
/* Get Last Update Time from Preferences */
SharedPreferences prefs = getPreferences(0);
lastUpdateTime = prefs.getLong("lastUpdateTime", 0);
/* Should Activity Check for Updates Now? */
if ((lastUpdateTime + (24 * 60 * 60 * 1000)) < System.currentTimeMillis()) {
/* Save current timestamp for next Check*/
lastUpdateTime = System.currentTimeMillis();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong("lastUpdateTime", lastUpdateTime);
editor.commit();

/* Start Update */
checkUpdate.start();

}
/* This Thread checks for Updates in the Background */
private Thread checkUpdate = new Thread() {
public void run() {
try {
URL updateURL = new URL("http://my.company.com/update");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
/* Convert the Bytes read to a String. */
final String s = new String(baf.toByteArray());
/* Get current Version Number */
int curVersion = getPackageManager().getPackageInfo("your.app.id",
0).versionCode;

int newVersion = Integer.valueOf(s);

/* Is a higher version than the current already out? */


if (newVersion > curVersion) {
/* Post a Handler for the UI to pick up and open the Dialog */
mHandler.post(showUpdate);
}
} catch (Exception e) {
}
};

/* This Runnable creates a Dialog and asks the user to open the Market */
private Runnable showUpdate = new Runnable(){
public void run(){
new AlertDialog.Builder(Test.this)
.setIcon(R.drawable.icon)
.setTitle("Update Available")
.setMessage("An update for is available!\\n\\nOpen Android Market and see the
details?")

.setPositiveButton("Yes", new DialogInterface.OnClickListener() {


public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked OK so do some stuff */
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://search?q=pname:your.app.id"));
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Cancel */
}
})
.show();
}
};
}

Get installed Applications with Name, Package Name, Version and Icon
9 votes 10 comments

This helper function retrieves all installed apps with the application name, package name, version-number and
-code as well as the icons. The method getPackages() returns an ArrayList with all the apps.
raw
copy
download
class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private Drawable icon;
private void prettyPrint() {
Log.v(appname + "\t" + pname + "\t" + versionName + "\t" + versionCode);
}
}
private ArrayList<PInfo> getPackages() {
ArrayList<PInfo> apps = getInstalledApps(false); /* false = no system packages */
final int max = apps.size();
for (int i=0; i<max; i++) {
apps.get(i).prettyPrint();
}
return apps;
}
private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for(int i=0;i<packs.size();i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue ;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());
res.add(newInfo);
}
return res;
}

Getting the Type of File as String


1 vote 2 comments

Get the Type of a File.


raw
copy
download

ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getExtensionFromMimeType(cR.getType(uri));

Open URL in android


1 vote 0 comments

To open the url in android


raw
copy
download
String url = "url";
Intent intent1 = new Intent(Intent.ACTION_VIEW);
intent1.setData(Uri.parse(url));
startActivity(intent1);

WebView: Activate JavaScript and Open Links Inside


1 vote 2 comments

This code activates JavaScript for a given WebView, and opens new link inside the WebBiew, not in the
Browser.
raw
copy
download
public class WebViewTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Set the Content View */
setContentView(R.layout.main);
/* Get the WebView */
WebView wv1 = (WebView) findViewById(R.id.wv1);
/* Activate JavaScript */
wv1.getSettings().setJavaScriptEnabled(true);
/* Prevent WebView from Opening the Browser */
wv1.setWebViewClient(new InsideWebViewClient());
}
/* Class that prevents opening the Browser */
private class InsideWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}

How to pass a dynamic URL to a Webview Activity


1 vote 0 comments

I don't really know if this way is correct, but it's simple and works (:
raw
copy
download
// ActivityOne
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
final Context context = this;
// ...
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
{
Intent intent = new Intent(context, WebViewActivity.class);
intent.setData(Uri.parse("http://www.androidsnippets.com"));
startActivity(intent);

long arg3)

}
// ...
}
// WebViewActivity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view);
webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(this.getIntent().getDataString());
}

Open URL in android


1 vote 0 comments

To open the url in android


raw
copy
download
String url = "url";
Intent intent1 = new Intent(Intent.ACTION_VIEW);
intent1.setData(Uri.parse(url));
startActivity(intent1);

WebView: Activate JavaScript and Open Links Inside


1 vote 2 comments

This code activates JavaScript for a given WebView, and opens new link inside the WebBiew, not in the
Browser.
raw
copy
download
public class WebViewTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Set the Content View */
setContentView(R.layout.main);
/* Get the WebView */
WebView wv1 = (WebView) findViewById(R.id.wv1);
/* Activate JavaScript */
wv1.getSettings().setJavaScriptEnabled(true);
/* Prevent WebView from Opening the Browser */
wv1.setWebViewClient(new InsideWebViewClient());
}
/* Class that prevents opening the Browser */
private class InsideWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}

Non-Blocking Web-Request
8 votes 11 comments

This code fetches content from the web without blocking the UI (runs in the background in a Thread). Once
finished, it posts a Handler that is picked up by the UI as soon as possible.
raw
copy
download

import
import
import
import
import

java.io.BufferedInputStream;
java.io.InputStream;
java.net.URL;
java.net.URLConnection;
org.apache.http.util.ByteArrayBuffer;

public class Iconic extends Activity {


private String html = "";
private Handler mHandler;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mHandler = new Handler();
checkUpdate.start();
}
private Thread checkUpdate = new Thread() {
public void run() {
try {
URL updateURL = new URL("http://iconic.4feets.com/update");
URLConnection conn = updateURL.openConnection();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
/* Convert the Bytes read to a String. */
html = new String(baf.toByteArray());
mHandler.post(showUpdate);
} catch (Exception e) {
}
};

private Runnable showUpdate = new Runnable(){


public void run(){
Toast.makeText(Iconic.this, "HTML Code: " + html, Toast.LENGTH_SHORT).show();
}
};
}

Executing a HTTP POST Request with HttpClient


31 votes 25 comments

This code executes a HTTP POST request with org.apache.http.client.HttpClient. Could be used in combination
with "Non-Blocking Web Requests".
raw
copy
download
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block

Convenient messaging between threads


2 votes 3 comments

The present snippet came up, when I struggled with messaging between different threads. The documentation
for the event loop (Looper, Handler and HandlerThread) is not that clear, at least for me. The idea is to use a
static thread-safe instance for emitting messages to other components even when they are running in different
threads. You can use a simple addressing mechanism or safely broadcast your message to all subscribed
components. This could be useful when you are dealing for example with a rendering thread, that needs to
communicate with your state machine(s), which in turn needs to broadcast state changes (which was my case).
import
import
import
import
import

android.os.Handler;
android.os.HandlerThread;
android.os.Message;
android.os.Handler.Callback;
android.util.Log;

/**
* The transceiver provides a convenient way to decorate an instance with receive and
transmit capabilities.
* It can (and this is encouraged) be used with the {@link Broker} instance.
* The naming thing is not part of the Transeiver's functionality, but may be useful while
debugging.
* This class can be used for subclassing or as a "has-a"-relation, as it is possible to
set
* an arbitrary {@link Callback } listener.
*
*/
public class Transceiver {
private String mName="Transceiver";
private static int ID=0;
private HandlerThread mHandlerThread;
private Handler mHandler;
// delegates the messages, when no proprietary callback
// is associated with the transeiver
private class HandlerListener implements Callback{
@Override
public boolean handleMessage(Message msg) {
return Transceiver.this.handleMessage(msg);
}
}
/**
* Creates a transceiver with an automatically generated name
*/
public Transceiver(){
mName = new String("Transceiver(" + ++ID + ")");
create(new HandlerListener());
}
/**
* Creates a transceiver with arbitrary name
* @param name
*/
public Transceiver(String name){
++ID;
mName = name;
create(new HandlerListener() );
}
/**
* Creates a transceiver with arbitrary name and an own listener
* @param name a custom name
* @param l your own listener
*/
public Transceiver(String name, Callback l){
++ID;
mName = name;

create(l);

private void create(Callback l){


mHandlerThread = new HandlerThread(getName());
mHandlerThread.start();
Log.d(mName, "Waiting for looper...");
// we need to wait (blocking) to get the looper instance
while(!mHandlerThread.isAlive()) {};
mHandler = new Handler(mHandlerThread.getLooper(), l);
Log.d(mName, "Ready");
}
/**
* @return The name of this transceiver
*/
public final String getName() { return mName; }
/**
* @return Its internal handler
*/
public final Handler getHandler() { return mHandler; }
/**
* The callback method for received messages. You can override it, when deriving
from Transceiver.
* @param msg the message
* @return true, if the message was handled.
*/
public boolean handleMessage(Message msg) { return false; }
}
// ------------------------------- BROKER ----------------------------------------import java.util.ArrayList;
import android.os.Handler;
import android.os.Message;
/**
* The broker is a kind of repository for {@link Handler} instances. It provides a simple
and very convenient mechanism to
* establish communication between different handlers. Just subscribe a handler instance
and use the returned address with
* this Broker. This class is thread safe, of course.
* Usage example:
* <code>
* this.MyCompAddr = Broker.instance.subscribe( new Handler() );
* // or, when using transceiver
* this.MyRendererAddr = Broker.instance.subscribe( new
MyTransceiver("Renderer").getHandler() );
* [...]
* // how to send messages
* Message m = Message.obtain();
* m.what = 1; // could be an identifier or op-code or whatever you want
* Bundle b= new Bundle(); // or use more complex (key,value)-pairs.
* b.putString("data", "Any Data");
* m.setData(b);
* Broker.instance.post(this.MyRendererAddr, m);
* </code>
*
*/
public class Broker {
/**
* The static instance.
*/
public static Broker instance=new Broker();
private ArrayList<Handler> mHandler;
private Broker()
{
mHandler = new ArrayList<Handler> ();
}

/**
* Subscribe a handler, so you can send messages easily to it.
* Mind there is no check for doubled subscription.
* @param h The handler
* @return The "address" for the handler
* @see {@link unsubscribe() }
*/
public synchronized int subscribe(Handler h){
ArrayList<Handler> hl=mHandler;
hl.add(h);
return hl.size()-1;
}
/**
* Unsubscribes a handler. Invalid addresses are ignored
* @param address
*/
public synchronized void unsubscribe(int address){
if(isAddressValid(address))
mHandler.remove(address);
}
protected synchronized final boolean isAddressValid(int address){
ArrayList<Handler> h=mHandler;
return (!h.isEmpty() && address >= 0 && address < h.size() );
}
/**
* Post a message to addressed receiver.
* @param address
* @param m
* @return true, if address exists, i.e. message could be delivered
*/
public synchronized boolean post(int address, Message m){
ArrayList<Handler> h=mHandler;
if(!isAddressValid(address))
return false;
h.get(address).sendMessage(Message.obtain(m));
return true;
}
/**
* Sends a message to all connected handler
* @param m The message
* @return The number of notified handler, e.g. send messages.
*/
public synchronized int broadcast(Message m)
{
ArrayList<Handler> h=mHandler;
int n=h.size();
for(int i=0; i<n; ++i)
{
h.get(i).sendMessage(Message.obtain(m));
}
return n;
}
}
// -----------------------------------------------------------------------------------// Some implementation examples
// -----------------------------------------------------------------------------------/**
* a place where I store my addresses.
* Read-only access to once set addresses is thread-safe!
*/
public class AddressPool {
public static int Subsystem1,Subsystem2,MyActivity;
}
// ## extending Transceiver (is-a-relation) ##
public class Subsystem2 extends Transceiver {
public final static String TAG="Subsystem2";
public final static int WHAT = 3862; // a magic number

public boolean handleMessage(Message m){

switch(m.what){
case Subsystem1.WHAT:
Log.i(TAG,"Received message from " + Subsystem1.TAG);
// attention: when answering we need a new message
Message msg= Message.obtain(m);
Broker.instance.post(AddressPool.Subsystem1, msg);
break;
case MyActivity.WHAT:
Log.i(TAG,"Received message from " + MyActivity.TAG );
break;
}
return true;

}
// ## wrapping/using Transceiver (has-a-relation) ##
package com.o1.android;
import java.util.Timer;
import java.util.TimerTask;
import com.o1.android.util.message.Broker;
import com.o1.android.util.message.Transceiver;
import
import
import
import
import
import

android.os.Bundle;
android.os.Handler;
android.os.HandlerThread;
android.os.Message;
android.os.Handler.Callback;
android.util.Log;

public class Subsystem1 extends TimerTask implements Callback{


public final static String TAG="Subsystem1";
public final static int WHAT = 175; // any identifier
private Transceiver mTransceiver;
private int mMyAddress=-1;
private Timer mTimer;
public Subsystem1(){
mTransceiver = new Transceiver(TAG, this);
mTimer = new Timer("SubsystemTimer");
}
public void onStart(){
mMyAddress = Broker.instance.subscribe(mTransceiver.getHandler());
// we use a timer to asynchronously post messages
mTimer.schedule(this, 0, 125);
}
public void onQuit(){
mTimer.cancel();
Broker.instance.unsubscribe(mMyAddress);
}
public final int getBrokerAddress() { return mMyAddress; }
@Override
public boolean handleMessage(Message m) {
switch(m.what){
case Subsystem2.WHAT:
Log.i(TAG,"Received message from " + Subsystem2.TAG);
break;
case MyActivity.WHAT:
Log.i(TAG,"Received message from " + MyActivity.TAG);
break;
}
// immediate response/delegate with a copy of our message
Broker.instance.post(AddressPool.MyActivity, Message.obtain(m));
return true;
}

@Override
public void run() {
Message m= new Message();
m.what=WHAT;
Broker.instance.post(AddressPool.MyActivity, m);
}
}
// ## connecting activities ##
public class MyActivity extends Activity implements Callback {
private Subsystem1 mSubsystem1;
//... other member fields
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* We have different types of transceiver implementations.
* One as "has" (subsystem1) and the other as "is"-relation.
*/
mSubsystem1 = new Subsystem1();
AddressPool.Subsystem2 = Broker.instance.subscribe(new Subsystem2().getHandler());
// additionally, we can use activities (or other components with loopers)
// mind that our activity implements Callback
AddressPool.MyActivity = Broker.instance.subscribe(new Handler(this));
// ... your stuff, e.g. a button that triggers messages
}
@Override
public void onStart(){
super.onStart();
mSubsystem1.onStart();
AddressPool.Subsystem1 = mSubsystem1.getBrokerAddress();
}
@Override
public void onDestroy(){
super.onDestroy();
mSubsystem1.onQuit();
}
@Override
public boolean handleMessage(Message msg) {
// handle your messages here
}
http://www.androidsnippets.com/convenient-messaging-between-threads