Professional Documents
Culture Documents
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;
}
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;
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;
}
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
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);
}
}
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;
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);
}
});
}
}
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: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;
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;
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;
}
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{
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;
}
}
================================================================
==============================
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);
}
}
});
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); }
}
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.
===============
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..."));
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
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);
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();
}
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;
}
}
}
This snippets configures listening for connectivity events (wifi, 3g) on and off
raw
copy
download
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();
}
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);
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);
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);
}
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;
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);
}
};
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();
}
0).versionCode;
};
/* 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();
}
};
}
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;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
/* 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);
}
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);
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);
};
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;
}
}
mainText.setText(sb);
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);
}
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);
3 votes 1 comment
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);
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);
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;
/* 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?")
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;
}
ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getExtensionFromMimeType(cR.getType(uri));
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;
}
}
}
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());
}
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;
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
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);
/**
* 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
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;
@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