我需要保持活動一個線程,該線程允許我發送數據,即使應用程序在後臺或被殺死(用戶將應用程序移開或關閉它)。Android保持活力IntentService
我知道我可以使用Service或IntentService。有人告訴我,使用IntentService,我可以使用通知,我正在做的就是像Telegram或Whatsapp這樣的應用程序,它可以持續監聽新消息。
我用服務,這是我的結果:
package test.com.connectionservices.Services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPListenerService extends Service {
static String UDP_BROADCAST = "UDPBroadcast";
DatagramSocket socket;
private void listenAndWaitAndThrowIntent() throws Exception {
try {
DatagramSocket clientSocket = null;
clientSocket = new DatagramSocket();
String data ;
byte[] sendData ;
InetAddress IPAddress = InetAddress.getByName("AN IP");
int i = 0;
while (true) {
data = "TEST THE SERVICE"+i;
sendData = data.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 21);
clientSocket.send(sendPacket);
i++;
}
} catch (Exception e) {
}
}
private void broadcastIntent(String senderIP, String message) {
Intent intent = new Intent(UDPListenerService.UDP_BROADCAST);
intent.putExtra("sender", senderIP);
intent.putExtra("message", message);
sendBroadcast(intent);
}
Thread UDPBroadcastThread;
void startListenForUDPBroadcast() {
UDPBroadcastThread = new Thread(new Runnable() {
public void run() {
try {
while (shouldRestartSocketListen) {
listenAndWaitAndThrowIntent();
}
//if (!shouldListenForUDPBroadcast) throw new ThreadDeath();
} catch (Exception e) {
Log.i("UDP", "no longer listening for UDP broadcasts cause of error " + e.getMessage());
}
}
});
UDPBroadcastThread.start();
}
private Boolean shouldRestartSocketListen = true;
void stopListen() {
shouldRestartSocketListen = false;
socket.close();
}
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
stopListen();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
shouldRestartSocketListen = true;
startListenForUDPBroadcast();
Log.i("UDP", "Service started");
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
這工作得很好,如果我去了其他應用或者我殺了採用Android的應用程序(在棒棒堂滑動的距離)也會有過程在洪水reciver的背景。
如何使用IntentService更改它?爲什麼我應該改變,有沒有辦法使用服務通知?