2010年1月31日 星期日

Mp3Player With Service

Activity:

public class Mp3PlayerWithService extends Activity implements OnClickListener {
private static final String TAG = "Mp3Interface";
private static Mp3PlayerWithService appRef = null;

private ImageButton btn, btn2, btn3;
public TextView tv;
private IBinder ib;

public static Mp3PlayerWithService getApp() {
return appRef;
}

public void btEvent(String data) {
setTitle(data);
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
appRef = this;

btn = (ImageButton) findViewById(R.id.PlayMP3);
btn2 = (ImageButton) findViewById(R.id.Stop);
btn3 = (ImageButton) findViewById(R.id.exit);
btn.setId(101);
btn2.setId(102);
btn3.setId(103);

btn.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);

tv = (TextView) findViewById(R.id.TextView01);
tv.setText("Ready");

bindService(new Intent(Mp3PlayerWithService.this, mp3Service.class),
mContection, Context.BIND_AUTO_CREATE);
}

private ServiceConnection mContection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder ibinder) {
ib = ibinder;
tv.setText(className.toString());
}

@Override
public void onServiceDisconnected(ComponentName className) {
}
};

public void onClick(View v) {
switch (v.getId()) {
case 101:
try {
ib.transact(1, null, null, 0);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 102:
try {
ib.transact(2, null, null, 0);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 103:
finish();
break;
}
}
}

Binder:


public class mp3PlayerBinder extends Binder{
private MediaPlayer mPlayer = null;
private Context ctx;

public mp3PlayerBinder(Context cx){
ctx = cx; }
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags){
if(code == 1)
this.play();
else if(code == 2)
this.stop();
return true;
}
public void play(){
if(mPlayer != null)
return;
mPlayer = MediaPlayer.create(ctx, R.raw.test);
mPlayer.start();
}
public void stop(){
if(mPlayer != null){
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
}

Service:


public class mp3Service extends Service{
private IBinder mBinder = null;
@Override
public void onCreate(){
mBinder = new mp3PlayerBinder(getApplicationContext());
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
}

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"
    >
TextView android:text="@+id/TextView01" android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content">
LinearLayout android:orientation="horizontal"
android:layout_height="wrap_content" android:layout_width="fill_parent">
ImageButton android:id="@+id/PlayMP3"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:src="@drawable/play" />
ImageButton android:id="@+id/Stop" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:src="@drawable/stop" />
ImageButton android:id="@+id/exit" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:src="@drawable/exit" />
      /LinearLayout>
/LinearLayout>

Thread& Handler

Activity:

public class ThreadAndHandler extends Activity implements OnClickListener {
private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;
private final int FP = LinearLayout.LayoutParams.FILL_PARENT;
private ProgressDialog progressDialog = null;
private myThread th1;
public TextView tv;
private Button btn, btn2, btn3;
private EventHandler h;

public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);

btn = new Button(this);
btn.setId(101);
btn.setText("test looper");
btn.setOnClickListener(this);
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(100, 50);
param.topMargin = 10;
layout.addView(btn, param);

btn2 = new Button(this);
btn2.setId(102);
btn2.setText("exit");
btn2.setOnClickListener(this);
layout.addView(btn2, param);

btn3 = new Button(this);
btn3.setId(103);
btn3.setText("send message");
btn3.setOnClickListener(this);

tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setText("");
LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(FP, WC);
param2.topMargin = 10;
layout.addView(tv, param2);
setContentView(layout);
// ------------------------
}

public void onClick(View v) {
switch (v.getId()) {
case 101:
String dialogTitle = "please wait…";
progressDialog = ProgressDialog.show(this, dialogTitle,
"Loading", true);
h = new EventHandler(Looper.myLooper());
//h = new EventHandler();
th1 = new myThread();
th1.start();
break;
case 102:
finish();
break;
}
}

// ------------------------------------------------
public class EventHandler extends Handler {
public EventHandler(){
super();
}
public EventHandler(Looper looper) {
super(looper);
}

@Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
tv.setText(msg.toString());
//Toast.makeText(ThreadAndHandler.this, msg.toString(), Toast.LENGTH_LONG).show();
setTitle((String) msg.obj);
}
}

// ---------------------------------------
class myThread extends Thread implements Runnable{
@Override
public void run() {
try {
sleep(6000);
} catch (Exception e) {
e.printStackTrace();
}
String obj = "mainThread....";
Message m = h.obtainMessage(1, 1, 1, obj);
h.sendMessage(m);
}
}
}



Reference:
http://www.android1.net/Topic.aspx?BoardID=11&TopicID=701
http://www.android1.net/Topic.aspx?BoardID=11&TopicID=625

2010年1月27日 星期三

Install JDK






JDK:Java Development Kit
We can download at the following URL.


Select the appropriate JDK software and click Download JDK.

And choose a Platform whilch we are used. Then press download.



After download finish, double click the exe file and install.

....



Now, The JDK software is installed on your computer.
Next, 我的電腦->內容




進階->環境變數->path->加上安裝路徑\bin





DONE!
Open cmd to check.
Type command "java -version".




Google Map View


MapViewGoogleAPI.java:

public class MapViewGoogleAPI extends MapActivity {
List mapOverlays;
Drawable drawable;
HelloItemizedOverlay itemizedOverlay;
MapController Mcontrol;
LinearLayout linearLayout;
MapView mapView;
ZoomControls mZoom;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linearLayout = (LinearLayout) findViewById(R.id.zoomview);
mapView = (MapView) findViewById(R.id.mapview);
mZoom = (ZoomControls) mapView.getZoomControls();
GeoPoint point = new GeoPoint(25043943,121533841);
Mcontrol = mapView.getController();
Mcontrol.animateTo(point);
Mcontrol.setZoom(15);
processThread();
linearLayout.addView(mZoom);
mapOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(R.drawable.androidmarker);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
OverlayItem overlayitem = new OverlayItem(point, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
private void processThread() {
new Thread() {
public void run() {
longTimeMethod();
for(int i = 0 ; i < i =" i+10">
Mcontrol.scrollBy(i, 0);
longTimeMethod();
}
GeoPoint newcenter = mapView.getMapCenter();
Mcontrol.animateTo(newcenter);
for(int k = 0 ; k <> Log.e("forloop", "do i in the forloop?");
Mcontrol.scrollBy(0, k);
}
newcenter = mapView.getMapCenter();
Mcontrol.animateTo(newcenter);
HelloItemizedOverlay newitemizedoverlay = new HelloItemizedOverlay(drawable);
OverlayItem newitem = new OverlayItem(newcenter, "", "");
newitemizedoverlay.addOverlay(newit
em);
mapOverlays.add(newitemizedoverlay);
}
}.start();
}

private void longTimeMethod() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e("mapview", e.getMessage());
}
}
}

HelloItemizedOverlay.java:

public class HelloItemizedOverlay extends ItemizedOverlay {
private ArrayList mOverlays = new ArrayList();
public HelloItemizedOverlay(Drawable defaultMarker) {
//super(defaultMarker);
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}

@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}

@Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}

}

main.xml:


result:

2010年1月25日 星期一

Popin' Pete



As a kid growing up in Fresno, California, a young Pete started down his road as a dancer by watching Soul Train and doing the robot.

In 1978 Pete started to learn the popping style from his older brother Sam who he would always watch dance. "I had to learn how to pop first because boogaloo was too difficult for me".

Popin Pete has gone on to innovate styles/moves like crazy legs, ET, spider man and sleepy style. Currently Pete is helping spread popping and boogaloo knowledge all over the world with the other EB members.

Oh my god! I love his move so much!!!!!!

Okinawa Churaumi Aquarium

Kuroshio Sea - 2nd largest aquarium tank in the world - (song is Please don't go by Barcelona) from Jon Rawlinson on Vimeo.

2010年1月21日 星期四

Set up SD card for your Android Emulator with Window XP




First,
start cmd. 開始->執行->cmd
Second,
You can access mksdcard in the tools/ directory of the SDK which like "C:\android-sdk-windows-1.6_r1\tools",
cd C:\android-sdk-windows-1.6_r1\tools
and then create a disk image like this:
mksdcard <size> <file>
mksdcard 1024M C:\sdcardImg\sdcard.img
wait about 30 second.
Third,
create a Emulator with Eclipse
window->Android SDK and AVD Manager->New, then choice a target and SD Card->File with img

Fourth,
Run the Emulator, then you will see the view like next picture at setting->SD card& phone storage.

But, how do we put files into the sdcard?
There are some example which put the mp3 file into sdcard.
First, open the cmd and we can use command "adb push 'file path' /sdcard" in the tools/ directory of the SDK.

Then we type command "adb shell" and type "ls -l /sdcard".
you can see the following picture, and you will find out the file is put in the /sdcard successfully.











we can check the file with Emulator, too.
music->songs



Reference:

Android 簡易msn

Client(Android Activity):

public class AndroidTestMSN extends Activity implements Runnable{
/** Called when the activity is first created. */
public static final String SERVERIP = "xxx.xxx.xxx.xxx";
public static final int SERVERPORT = 13267;
public Button connectButton = null;
public Button sendButton = null;
public EditText inputMessage = null;
public EditText messageContent = null;
private Socket socket;
private BufferedReader br = null;
private String data = null;
private PrintWriter out = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
connectButton = (Button) this.findViewById(R.id.connectBtn);
connectButton.setText("Connect Server");
sendButton = (Button) this.findViewById(R.id.sendBtn);
sendButton.setText("Send message");
inputMessage = (EditText) this.findViewById(R.id.message_input);
inputMessage.setText("edit message");
messageContent = (EditText) this.findViewById(R.id.message_content);
/**
* set the listener of the connectBtn. 1.connect with the server,and set
* the time before this conversation. 2.get the input and out put stream
* of the socket.
*/
connectButton.setOnClickListener(new OnClickListener() {
// messageContent = (EditText) findViewById(R.id.message_content)
public void onClick(View v) {
Log.e("test connectBtn","prepare to connect with the server..");
try {
socket = new Socket(InetAddress.getByName(SERVERIP),SERVERPORT);
//socket = new Socket(SERVERIP, SERVERPORT);
if (socket.isConnected()) {
// Log.e("time", new
// String().valueOf(System.currentTimeMillis()));
messageContent.setText(new Timestamp(System.currentTimeMillis()).toString()
+ "\n");
}
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
/**
* set the listener of the sendBtn. 1.get the nick name ,if it is
* null,set is as "android". 2.send the message to the server.
*/
sendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (out != null) {
String nickName = null;
nickName = "android";
Log.e("test conntetion", "test send data button");
out.println(nickName + ":"
+ inputMessage.getText().toString());
data = new String(nickName + ":"+ inputMessage.getText().toString());
messageHandler.sendEmptyMessage(0);
out.flush();
}
inputMessage.setText("");
}
});
Thread t = new Thread(this);
t.start();
}//onCreate
public void run() {
while (true) {
try {
if (br != null) {
data = new String(br.readLine());
Log.e("get message", data);
messageHandler.sendEmptyMessage(0);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/**
* when messageHandler.sendEmptyMessage(0); runs,the handler will call the
* call back fucntion handleMessage to append the data from the server.
*/
private Handler messageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
messageContent.append(data);
messageContent.append("\n");
}
};
}


Server:

public class myServer {
public static final String SERVERIP = "127.0.0.1";
public static final int SERVERPORT = 13267;
public static String s = " ";
public static String inputS = " ";
public static InputStream Is;
public static OutputStream Os;
public static DataInputStream DIS;
public static PrintStream PS;
private static String data = null;
private static BufferedReader br = null;
@SuppressWarnings("deprecation")
public static void main(String args[]) {
ServerSocket server;
Socket socket;


try {
System.out.println("S: Connecting...");
// 在端口4321注冊服務
server = new ServerSocket(SERVERPORT);
socket = server.accept(); // 監聽窗口,等待連接

System.out.println("server ok");
System.out.println("************************************************");
System.out.println("");

// 獲得對應Socket的輸入/輸出流
Is = socket.getInputStream();
Os = socket.getOutputStream();// 建立數據流
DIS = new DataInputStream(Is);
PS = new PrintStream(Os);
DataInputStream in = new DataInputStream(System.in);
Thread receive = new Thread(new Runnable() {
public void run() {
while (true) {
try {
if (DIS != null) {
inputS = DIS.readLine();// 讀入從client傳來的字符串
System.out.println("client said:" + inputS); // 打印字符串
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error1:" + e);
}
}
}// run
});
receive.start();
while (true) {
System.out.println("");
System.out.println("please wait client's message...");
System.out.println("");

// 原本的client input
// inputS = DIS.readLine();// 讀入從client傳來的字符串
// System.out.println("client said:" + inputS); // 打印字符串
// if (inputS.trim().equals("BYE"))
// break; // 如果是"BYE",就退出
System.out.print("you say:");
s = in.readLine(); // 讀取用戶輸入的字符串
PS.println(s); // 將讀取得字符串傳給client
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出
}//while

// 關閉連接
DIS.close(); // 關閉數據輸入流
PS.close(); // 關閉數據輸出流
Is.close(); // 關閉輸入流
Os.close(); // 關閉輸出流
socket.close(); // 關閉sockey
System.out.println("Disconnect");
} catch (Exception e) {
System.out.println("Error2:" + e);
}
}//main
}

layout:




<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout android:id="@+id/widget31"
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android">
        <Button android:id="@+id/connectBtn" android:layout_width="147px"
                android:layout_height="42px" android:text="ConnectServer"
                android:layout_x="167px" android:layout_y="2px">
        </Button>
        <EditText android:id="@+id/message_content"
                android:layout_width="315px" android:layout_height="276px"
                android:textSize="18sp" android:layout_x="4px" android:layout_y="41px">
        </EditText>
        <EditText android:id="@+id/message_input"
                android:layout_width="230px" android:layout_height="49px"
                android:text="Message" android:textSize="18sp" android:layout_x="5px"
                android:layout_y="345px">
        </EditText>
        <Button android:id="@+id/sendBtn" android:layout_width="81px"
                android:layout_height="55px" android:text="Send" android:layout_x="238px"
                android:layout_y="345px">
        </Button>
</AbsoluteLayout>



result:


2010年1月20日 星期三

Java Socket

Server:

public class myServer {
public static final String SERVERIP = "127.0.0.1";
public static final int SERVERPORT = 13267;
public static void main(String args[]) {
ServerSocket server;
Socket socket;
String s;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;

try {
// 在端口4321注冊服務
server = new ServerSocket(SERVERPORT);
socket = server.accept(); // 監聽窗口,等待連接

System.out.println("server ok");
System.out
.println("************************************************");
System.out.println("");

// 獲得對應Socket的輸入/輸出流
Is = socket.getInputStream();
Os = socket.getOutputStream();
// 建立數據流
DIS = new DataInputStream(Is);
PS = new PrintStream(Os);
DataInputStream in = new DataInputStream(System.in);
while (true) {
System.out.println("");
System.out.println("please wait client's message...");
System.out.println("");
s = DIS.readLine(); // 讀入從client傳來的字符串
System.out.println("client said:" + s); // 打印字符串
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出
System.out.print("you say:");
s = in.readLine(); // 讀取用戶輸入的字符串
PS.println(s); // 將讀取得字符串傳給client
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出

}

// 關閉連接
DIS.close(); // 關閉數據輸入流
PS.close(); // 關閉數據輸出流
Is.close(); // 關閉輸入流
Os.close(); // 關閉輸出流
socket.close(); // 關閉sockey
} catch (Exception e) {
System.out.println("Error:" + e);
}
}
}

Client:

public class myClient{
public static final String SERVERIP = "127.0.0.1";
public static final int SERVERPORT = 13267;
public static void main(String args[]) {
Socket socket;
String s = "yxfsoft@263.net";
String len;
InputStream Is;
OutputStream Os;
DataInputStream DIS;
PrintStream PS;
try {
socket = new Socket(SERVERIP, SERVERPORT);
System.out.println("client ok");
System.out
.println("************************************************");
System.out.println("");
// 獲得對應socket的輸入/輸出流
Is = socket.getInputStream();
Os = socket.getOutputStream();
// 建立數據流
DIS = new DataInputStream(Is);
PS = new PrintStream(Os);
DataInputStream in = new DataInputStream(System.in);
while (true) {
System.out.print("you say:");
s = in.readLine(); // 讀取用戶輸入的字符串
PS.println(s); // 將讀取得字符串傳給server
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出
else {
System.out.println("");
System.out.println("please wait server's message...");
System.out.println("");
}
s = DIS.readLine(); // 從服務器獲得字符串
System.out.println("server said:" + s); // 打印字符串
if (s.trim().equals("BYE"))
break; // 如果是"BYE",就退出

}
// 關閉連接
DIS.close(); // 關閉數據輸入流
PS.close(); // 關閉數據輸出流
Is.close(); // 關閉輸入流
Os.close(); // 關閉輸出流
socket.close(); // 關閉socket
} catch (Exception e) {
System.out.println("Error:" + e);
}
}
}

Android Socket


呼~用了好幾個小時才完成

Client:



public class SocketTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Thread cThread = new Thread(new TCPClient());
cThread.start();
}
}

public class TCPClient implements Runnable {

public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("xxx.xxx.xxx.xxx");
//因為使用模擬器,所以必須填上host的IP位置,若用127.0.0.1會連不到,我猜可能是模擬器會連上模擬器的127.0.0.1了
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, 13267);
String message = "Hello from Client android emulator";
try {
Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())), true);
out.println(message);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
} catch (Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
//socket.close();
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
}
}

Server:

public class TCPDesktopServer implements Runnable {

public static final String SERVERIP = "127.0.0.1";
public static final int SERVERPORT = 13267;

public void run() {
try {
System.out.println("S: Connecting...");
ServerSocket serverSocket = new ServerSocket(SERVERPORT);
while (true) {
Socket client = serverSocket.accept();
System.out.println("S: Receiving...");
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
String str = in.readLine();
System.out.println("S: Received: '" + str + "'");
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();

} finally {
//client.close();
System.out.println("S: Done.");
}
}
} catch (Exception e) {
System.out.println("S: Error");
e.printStackTrace();
}
}

public static void main(String a[]) {
Thread desktopServerThread = new Thread(new TCPDesktopServer());
desktopServerThread.start();
}
}