당신은 바로 Service
는 작업에 적합한 도구입니다 가정에 발견하지 않았습니다.
는 Services | Android Developers
서비스가 백그라운드에서 실행 시간이 긴 작업을 수행 할 수 있으며, 사용자 인터페이스를 제공하지 않는 응용 프로그램 구성 요소입니다 참조하십시오.
소켓 유지는 장기간 백그라운드 작업을 수행 할 수 있습니다.
나는 다음을 수행하는 사용자를 위해이 예제를 만들어 :
- 가/연결 다시 연결하고 독서에 대한
Thread
을 시작합니다 InputStream
- 신고
Notification
- 닫기에서 현재 연결 상태
onCreate()
에서 Socket
및 Thread
을 중지하십시오. onDestroy()
는
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MyService extends Service implements Runnable {
private static final int NOTIFICATION_ID = 1;
private boolean mRunning = false;
private Thread mThread;
private Socket mSocket;
private InputStream mInputStream;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
setNotificationMessage("Service created");
if (mThread == null) {
mRunning = true;
mThread = new Thread(this);
mThread.start();
}
}
@Override
public void run() {
try {
while (mRunning) {
try {
setNotificationMessage("Connecting");
mSocket = new Socket();
mSocket.connect(new InetSocketAddress("192.168.56.1", 9899));
mInputStream = mSocket.getInputStream();
setNotificationMessage("Connected");
for (int c = mInputStream.read(); c > -1; c = mInputStream.read()) {
setNotificationMessage("Connected: " + (char) c);
}
} catch (UnknownHostException ignored) {
setNotificationMessage("Unknown host");
} catch (IOException ignored) {
setNotificationMessage("Disconnected");
close();
}
try {
// Reconnect delay
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
} finally {
// Will eventually call onDestroy()
stopSelf();
}
}
private void setNotificationMessage(CharSequence message) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("Connection status");
builder.setContentText(message);
NotificationManagerCompat nm = NotificationManagerCompat.from(this);
nm.notify(NOTIFICATION_ID, builder.build());
}
private void close() {
if (mInputStream != null) {
try {
mInputStream.close();
mInputStream = null;
} catch (IOException ignored) {
}
}
if (mSocket != null) {
try {
mSocket.close();
mSocket = null;
} catch (IOException ignored) {
}
}
}
@Override
public void onDestroy() {
if (mThread != null) {
mRunning = false;
close();
while (true) {
try {
mThread.interrupt();
mThread.join();
mThread = null;
break;
} catch (InterruptedException ignored) {
}
}
}
setNotificationMessage("Service destroyed");
super.onDestroy();
}
}
방법은 무엇입니까 스레드의 조인 MyService.java? –
Join은 스레드의 실행이 완료 될 때까지 대기합니다. [Thread | Android 개발자] (http://developer.android.com/reference/java/lang/Thread.html#join()) – Nicklas