2
DataService://overover
package com.example.sockettest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
public class DataService extends Service {
private String TAG = "";
private IBinder binder = new DataService.DataBinder();
ServerSocket serivce = null;
public String line = null;
@SuppressLint("NewApi")
@Override
public void onCreate() {
Log.v("weather->DataService", "onCreate");
super.onCreate();
}
@Override
public void onDestroy() {
Log.v(TAG, "onDestroy");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.v(TAG, "onStartCommand");
try {
serivce = new ServerSocket(30000);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
new Thread(new AndroidRunable()).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
Log.v("DataService.java", "onBind");
return new CarRecordBinder(this);
}
public class CarRecordBinder extends Binder {
private DataService mService;
public CarRecordBinder(DataService carRecordService) {
this.mService = carRecordService;
}
public DataService getService() {
return mService;
}
}
public class DataBinder extends Binder {
// 返回本地服务
public DataService getService() {
return DataService.this;
}
}
public class AndroidRunable implements Runnable {
@Override
public void run() {
// 向android客户端输出hello worild
String line = null;
InputStream input;
OutputStream output;
String str = "hello world!";
Socket socket = null;
while (true) {
//等待客户端连接
try {
socket = serivce.accept();
//向客户端发送信息
input = socket.getInputStream();
BufferedReader bff = new BufferedReader(
new InputStreamReader(input));
//半关闭socket
socket.shutdownOutput();
//获取客户端的信息
char buf[] = new char[100] ;
while (( bff.read(buf ) ) != -1) {
line = buf.toString();
sendBroadcast("com.dede.dede");
}
//关闭输入输出流
bff.close();
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void sendBroadcast(String str) {
Intent intent = new Intent(str);
sendBroadcast(intent);
}
public String getLine()
{
return line;
}
}