Skip to content

Instantly share code, notes, and snippets.

@cool-delete
Created October 31, 2016 18:34
Show Gist options
  • Save cool-delete/f03876d63c02a6f7a676054ef3ebf07c to your computer and use it in GitHub Desktop.
Save cool-delete/f03876d63c02a6f7a676054ef3ebf07c to your computer and use it in GitHub Desktop.
监听
package cool_delete.socket_connect_pull_push;
import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyService extends Service {
private Socket client;
private ServerSocket serverSocket;
public MyService() {
try {
serverSocket = new ServerSocket(configuration.port);
System.out.println("已监听8848");
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
// System.out.println("启动");
// startService(new Intent(this, innerserv.class));
if (!intent.getStringExtra("ip").equals("")) {
new Thread(new Runnable() {
@Override
public void run() {
try {
sendMsgTo(intent);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
pullmsg();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
return super.onStartCommand(intent, flags, startId);
}
private void pullmsg() throws IOException {
Socket accept = serverSocket.accept();
System.out.println("已获取");
BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
String s = reader.readLine();
System.out.println("拿到的内容是___" + s);
sendBroadcast(new Intent("sock_getMsg").putExtra("msg", s));
}
private void sendMsgTo(Intent intent) throws IOException {
String ip = intent.getStringExtra("ip");
client = new Socket(ip, configuration.port);
OutputStream outputStream = client.getOutputStream();
String msg = intent.getStringExtra("msg");
outputStream.write(msg.getBytes());
System.out.println(ip + "发送的内容是__" + msg);
System.out.println(client.isConnected() + "是否连接");
outputStream.flush();
outputStream.close();
System.out.println("已发送数据");
client.close();
}
public class innerserv extends Service {
public innerserv() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
keepaLive(MyService.this, this);
return super.onStartCommand(intent, flags, startId);
}
private void keepaLive(MyService myService, innerserv innerserv) {
myService.startForeground(1, new Notification());
// innerserv.startForeground(1, new Notification());
innerserv.stopSelf();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment