Android
Installation:
Download and install SDK
Install via SDK manager and AVD manager
Add C:\Program Files (x86)\Android\android-sdk\tools to environment path
Install ADT plugin in Eclipse by entering “ADT Plugin” for the Name and the following URL for the Location: https://dl-ssl.google.com/android/eclipse/
The first time to lauch AVD may take rather long time, just be patient. Leave the launched AVD open until your project is finished.
Possible problems during installation:
java basis is unresolved: Project->Properties->Java Build Path->Libraries, add JRE lib
Android is unresolved: Project->Properties->Android, choose project build target and apply. For some Eclipse versions, clean and rebuild.
Resource:
Begining Android2: code is downloaded from https://www.apress.com
Application:
Application consists of Activity, Service, BroadcastReceiver, and Content Provider, in which Activity is a regular App, Service can run independently in the background, such as MP3 player, BroadcastReceiver reacts to outcoming events, Content Provider save data via SQLite or share data with other applications.
activity: Most common application. [AndroidManifest example] [activity cycle]
service: Similar with activity but without user interface. [AndroidManifest example] [service cycle]
independent service
1
2
3
4final Intent intent = new Intent();
intent.setAction("org.crazyit.service.FIRST_SERVICE");
startService(intent);
stopService(intent);service has connection with activity via
IBinder1
2
3
4
5
6
7
8
9BindService.MyBinder binder;
private ServiceConnection conn = new ServiceConnection(){
public void onServiceConnected(ComponentName name, IBinder service){
binder = (BindService.MyBinder) service;
}
public void onServiceDisconnected(ComponentName name){}
};
bindService(intent, conn, Service.BIND_AUTO_CREATE);
unbindService(conn);to create a new thread, extend class
IntentServicefor interprocess communication, use AIDL, i.e., extends
Stubas IBinder interface. The others are the same asService.
receiver: a global listener. AndroidManifest example
1
2
3
4Intent intent = new Intent();
intent.setAction("org.crazyit.action.CRAZY_BROADCAST");
intent.putExtra("msg", "hello world");
sendBroadcast(intent);use IntentFilter to filter the received broadcast
1
2
3IntentFilter filter = new IntentFilter();
filter.addAction(MusicBox.CTL_ACTION);
registerReceiver(serviceReceiver, filter);provider: globally share data. AndroidManifest example
The joint point is Uri:
content://org.crazyit.providers.dictprovider/words/idContentProvider: an extended class
public class DictProvider extends ContentProviderwhich providesquery,insert,delete,updatefunctions.ContentResolver:
1
2ContentResolver contentResolver = getContentResolver();
contentResolver.insert(Words.Word.DICT_CONTENT_URI, values);Most system applications provide their own ContentProvider, we need to know their Uri.
Adapter:
Adapters are the link between a set of data (ArrayList, Cursor) and the AdapterView (ListView, GridView, Spinner) that displays the data. AdapterViews are ViewGroups that display child views given to it by an adapter.
ArrayAdapter:
In the simplest case, just use the String array
items1
2
3ArrayAdapter<String>aa = new ArrayAdapter<String>(this, adnroid.R.layout.simple_spinner_item, items);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);Extend ArrayAdapter to satisfy your own needs,
1
2
3
4MyArrayAdapter adapter = new MyArrayAdapter(this, R.layout.my_list_view, MyObjectItemData);
ListView listViewItems = new ListView(this);
listViewItems.setAdapter(adapter);
listViewItems.setOnItemClickListener(new OnItemClickListenerListViewItem());The code for class
MyArrayAdapteris here. The code for classOnItemClickListenerListViewItemis here. Note hereinflateis used to convert XML format to View. One trick is to check whether convertView is null so that duplicated reflation could be avoided, otherwise your device would be slowed down when crolling the screen. ConvertView can be bined with a newly defined class by usingsetTagandgetTag. When the adapter is changed (e.g., add a new row),adapter.notifyDataSetChanged().CursorAdapter:
1
2SimpleCursorAdapter adapter=new SimpleCursorAdapter(this, R.layout.row, constantsCursor, new String[] {"tag", "value"}, new int[] {R.id,tag, R.id.value});
listviewItems.setAdapter(adapter);Extend CursorAdapter, see here
XML format:
Use XML to format Layout: In XML file,
android:id="@+id/button. In Java,btn=(Button)findViewById(R.id.button). Similarly, in XML file,android:id="@string/app_name, in Java,Resources myres = getResources(); myres.getString();.Use XML to format componenet style: in res\values\text_style.xml, in \res\layout\main.xml,
style="@style/style2".Use XML to format window style: in res\values\window_style.xml, in
onCreate()function, addsetTheme(R.style.crazytheme), or<application android:theme="@style/crazytheme">.Use XML to format menu style: \res\menu\contextmenu_style.xml optionmenu_style.xml.
1
2
3MenuInflater inflator = new MenuInflater(this);
inflator.inflate(R.menu.my_menu, menu);
//return super.onCreateOptionsMenu(menu);Use XML to inflate a view and thus format dialogue style, click login.xml
1
2TableLayout loginForm = (TableLayout)getLayoutInflater().inflate(R.layout.login, null);
ad.setView(loginForm);
Event:
Add EventListener: there exist several types of implement. We take the most common event “click” as an example to demonstrate five types of implements.
- Override function
onClickin classOnClickListener1
2
3button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
}); Extend class
OnClickListener, essentially equal to a)1
2
3
4
5
6private Button1_OnClickListener mListener1 = new Button1_OnClickListener();
class Button1_OnClickListener implements OnClickListener {
public void onClick(View v) {
}
mButton1.setOnClickListener(mListener1);Bind event listener in XML
1
2
3android:onClick="clickHandler"
function clickHandler(){For key event:
1
2
3new OnKeyListener(){
public boolean onKey(View source, int keyCode, KeyEvent event{
switch(event.getKeyCode())For long click:
1
2new OnLongClickListener{
public boolean onLongClick(View source){
- Override function
Override Recall Function: extend View or Activity class to override event recall functions.
* Extends Activity Class1
2
3
4
5public class TestEvent2 extends Activity implements OnClickListener{
public void onClick(View v) {
public class TestEvent2 extends Activity{
boolean onKeyDown(int keycode, KeyEvent event){- Extends View Class
1
2
3
4
5public class MyButton extends Button{
public boolean onKeyDown(int keyCode, KeyEvent event){
public class DrawView extends View{
public boolean onTouchEvent(MotionEvent event){
- Extends View Class
Layout:
Common attributes
1
2
3
4android:layout_width|height="fill_parent"|"wrap_content"|"10dip"
android:gravity="center_horizontal"|"right"
android:background="#FF909090"
android:padding="3dip"FrameLayout: fundamental layout, allow overlap or replacement for flexible usage.
LinearLayout: example code
1
android:layout_weight="1"
AbsoluteLayout: example code
1
android:layout_x|layout_y="250dip"
RelativeLayout: example code
1
2
3
4
5android:layout_below="@id/label"
android:layout_toLeftOf="@id/ok"
android:layout_alignParentRight="true"
android:layout_alignTop="@id/ok"
android:layout_marginLeft="10dip"TableLayout: example code
1
2android:layout_span="3"
android:layout_column="2"Make the layout scrollable, add
<ScrollView>as in example code
Componenet:
EditText | TextView example code
RadioGroup example code
CheckBox example code
Spinner: dropdown menu example code
ListView: example code
GridView: example code
OptionsMenu: in the corner of screen example code
ContextMenu: long press to show the menu. example code.
Advanced Componenet:
Picker: The DatePicker code is as follows and the TimePicker code is similar.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17Calendar dateAndTime=Calendar.getInstance();
DatePickerDialog.OnDateSetListener mydiag=new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
dateAndTime.set(Calendar.YEAR, year);
dateAndTime.set(Calendar.MONTH, monthOfYear);
dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
Button btn=(Button)findViewById(R.id.dateBtn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new DatePickerDialog(ChronoDemo.this, mydiag, year, month, day).show();
}
});Number picker
1
2
3
4
5
6
7
8
9
10
11
12NumberPicker np = (NumberPicker) findViewById(R.id.npId);
np.setOnValueChangedListener(new OnValueChangeListener()
{
public void onValueChange(NumberPicker picker, int oldVal, int newVal)
{
tv.setText(String.valueOf(newVal));
}
});
np.setMaxValue(100);
np.setMinValue(0);Toast
1
2
3import android.widget.Toast;
Toast.makeText(Demo.this, "warning msg", Toast.LENGTH_LONG).show();Notification example code
Alert dialog example code
Dial phone number
add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>java code
1
2Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + inputStr));
startActivity(phoneIntent);
Send message
add permission in AndroidManifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>java code
1
2
3SmsManager smsManager = SmsManager.getDefault();
PendingIntent sentIntent = PendingIntent.getBroadcast(act, 0, new Intent(), 0);
smsManager.sendTextMessage(addressStr, null,contentStr, sentIntent, null);
Gallary example code
Timer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17new Timer().schedule(new TimerTask()
{
public void run()
{
handler.sendEmptyMessage(0x123);
}
}, 0, 200);
Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
if (msg.what == 0x123){
}
super.handleMessage(msg);
}
};
Gist
<uses-sdk android:minSdkVersion="2" />indicates the minimum requirement of SDK.<uses-permission android:name="android.permission.SEND_SMS" />indicates the required permission.To utilize the resouce in res/values: in java code, , R.id….R.string….; in XML file, @id/…..@string/……
Set no title or fullscreen, add the following code in
AndroidManifest.xml1
2
3
4
5
6
7
8
9
10
11
12
13
14
15<activity android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
```
1. There are two types of intents: explicit and implicit. In explicit intents you provide the name of the Activity class. In implicit intents, you tell the system what to do rather than name the Activity class to launch.
## Game Development ##
1. Prepare music and image resources uder folder "res"
1. Use Handler in the MainActivity
```android
hd=new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what)MenuView
1
2
3public class ViewMainMenu extends SurfaceView implements SurfaceHolder.Callback{
public void onDraw(Canvas canvas){
public void surfaceCreated(SurfaceHolder holder) {Create on thread for each function
1
public class KeyThread extends Thread{
Use GLRender for GameView, android opengl
1
2
3
4
5
6
7
8class MySurfaceView extends GLSurfaceView {
public MySurfaceView(Context context) {
super(context);
mRenderer = new SceneRenderer();
setRenderer(mRenderer);
setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);
}
class SceneRenderer implements GLSurfaceView.Renderer{

