我在android中有一個應用程序,它是一種TCP/IP連接的客戶端...這個應用程序有接收來自GPS提供商的GPSt數據並將其發送到服務器我的TCP/IP連接的一面。在android中檢測互聯網連接
只有在沒有互聯網連接的GPS數據我必須將它保存在一個數據庫....而當我再次有互聯網連接,我不得不重新啓動客戶端,並重新連接到我的服務器和發送數據。
提問:我1.How可以檢測機器人的網絡連接(我的應用程序是在模擬器中運行)
,只要我發現互聯網連接來問我的線程客戶端重新連接2.Is可能,服務器???
這裏是我的代碼方案:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
cThread = new Thread(new ClientThread(syncToken));
cThread.start();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListener);
}
public void onLocationChanged(Location loc) {
if (loc != null) {
latitude = (int) (loc.getLatitude() * 1E6);
longitude = (int) (loc.getLongitude() * 1E6);
}
}
GeoPoint p = new GeoPoint(latitude, longitude);
// geoPointsArray.add(p);
db.insertData1(longitude, latitude);
}
public class ClientThread implements Runnable {
Object syncToken;
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, 7001);
Log.d(" ", "Clientul s-a conect");
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
} catch (IOException e) {
System.err
.println("Couldn't get I/O for the connection to host");
}
try {
os = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
while (true) {
synchronized (syncToken) {
try {
syncToken.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (socket != null && os != null) {
try {
//send data through the socket
}catch (Exception e){
e.printStackTrace();
}
i++;
}
}
}
}
編輯:
這是我做的:
private NetworkStateReceiver mNetSateReceiver = null;
private class NetworkStateReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info =connectivity.getActiveNetworkInfo();;
if (info != null && info.isConnectedOrConnecting()) {
System.out.println(" internet connection!");
}
else
System.out.println("no internet connection");
}
}
onCreate(){
registerReceiver(mNetSateReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
syncToken = new Object();
cThread = new Thread(new ClientThread(syncToken));
cThread.start();
}
public void onDestroy(){
super.onDestroy();
db.close();
unregisterReceiver(mNetSateReceiver);
}
我明白,每次我的狀態連接更改我的onReceive()被調用....這意味着我要開始我的線程中的onReceive ()當有互聯網連接?
我有點迷惑,如果ü可以清理一點點的事情對我來說......我應該從哪裏開始這一意圖,美告訴我? THX
正如有關重新啓動我的線程,並迫使它重新連接到我的服務器怎麼可能呢?:-S – adrian 2011-06-04 10:50:32
另一個交易是:我應該在onCreate()中驗證互聯網連接嗎?: - S – adrian 2011-06-04 10:59:06
在啓動您的線程前,運行'getActiveNetworkInfo()' – wired00 2011-06-04 11:07:44