Android 如何知道可以连接哪些在线数据库
我正在构建一个与商店相关的客户端服务器android应用程序,我希望(当用户接近2或3家商店的数据库在线时)我的应用程序能够理解他可以连接到其中一家商店的数据库,并将其列在屏幕上。(当我们想连接到互联网时,可用WIFI的情况如何) 我如何才能做到这一点?Android 如何知道可以连接哪些在线数据库,android,database,Android,Database,我正在构建一个与商店相关的客户端服务器android应用程序,我希望(当用户接近2或3家商店的数据库在线时)我的应用程序能够理解他可以连接到其中一家商店的数据库,并将其列在屏幕上。(当我们想连接到互联网时,可用WIFI的情况如何) 我如何才能做到这一点? 我希望我能说清楚我在找什么 如果我错了,请纠正我。您正在编写一个应用程序,可以从服务器访问数据,而服务器/数据库属于某个存储 如果我对您的问题的理解是正确的,请执行以下操作: 创建侦听连接更改的连接广播 创建一个GPS管理器,将当前位置与基于
我希望我能说清楚我在找什么 如果我错了,请纠正我。您正在编写一个应用程序,可以从服务器访问数据,而服务器/数据库属于某个存储 如果我对您的问题的理解是正确的,请执行以下操作:
- 创建侦听连接更改的连接广播
- 创建一个GPS管理器,将当前位置与基于门店位置的位置进行比较
- 如果在一个或多个存储区的范围内,并且连接可用,则通过restfull请求查询服务器,在服务器端启动查询,查看是否得到任何结果(我不知道是否存在特定的查询来检查从服务器端代码到数据库的数据库连接)。如果得到结果,则数据库可用,将结果从服务器发送回客户端,并将数据库/存储列为可用
private Context _context;
private State _state;
private boolean _listening;
private String _reason;
private boolean _isFailOver;
private NetworkInfo _networkInfo;
private NetworkInfo _otherNetworkInfo;
private ConnectivityBroadcastReceiver _receiver;
/**
* The broadcast that listens to connectivity changes(wifi, mobile network etc)
* */
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
/**
* Called when connectivity state changes
*
* @param Context the context
* @param Intent the intent containing the information about the change
* */
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(!action.equals(ConnectivityManager.CONNECTIVITY_ACTION) || _listening == false) {
Log.w(TAG, "onReceived() called with " + _state.toString() + " and " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
//Set the state according to current connectivity.
if(noConnectivity) {
_state = State.NOT_CONNECTED;
} else {
_state = State.CONNECTED;
}
//If current state is CONNECTED. Start background services, otherwise stop services.
switch(_state) {
case CONNECTED:
//Do stuff when connected
break;
case NOT_CONNECTED:
//Do stuff if not connected
break;
}
_networkInfo = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
_otherNetworkInfo = (NetworkInfo)intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
_reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
_isFailOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
Log.d(TAG, "onRecieve(): _networkInfo= " + _networkInfo + " _otherNetworkInfo= " + (_otherNetworkInfo == null ? "[none]" : _otherNetworkInfo +
" noConn= " + noConnectivity) + " _state= " + _state.toString());
}
};
我没有发布全部代码。我在康涅狄格州的街道上写了一封信。但是对于给定的代码,您应该能够走得足够远。请注意,在代码状态中有一个枚举,其中包含3个值:CONNECTED、NOT_CONNECTED、UNKNOWN
至于全球定位系统经理:
/**
* <h1>GPSManager</h1>
*
* <p>
* Manager for GPS tracking.
* Able to enable and disable GPS tracking for the application.
* </p>
* */
public class GPSManager {
public static final String TAG = "LocationFinder";
private double _lat;
private double _lon;
private float _accuracy;
private Context _context;
private LocationManager _locManager;
private LocationListener _locListener;
private static GPSManager _instance;
/**
* Constructor.
*
* @param context The context of the caller.
* */
private GPSManager(Context context) {
this._context = context;
this._locListener = new LocationTracker();
}
/**
* GPSManager is singleton. Retrieve the shared instance.
*
* @param context The context of the caller.
* @return GPSManager An instance of the GPSManager class.
* */
public static synchronized GPSManager getInstance(Context context) {
if(_instance == null) {
_instance = new GPSManager(context);
}
return _instance;
}
/**
* Start tracking GPS locations.
* */
public void startGpsTracking() {
_locManager = (LocationManager)_context.getSystemService(Context.LOCATION_SERVICE);
_locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, _locListener);
}
/**
* Stop tracking GPS locations.
* */
public void stopGpsTracking() {
_locManager.removeUpdates(_locListener);
_locManager = null;
}
/**
* Retrieve the latitude from the GPSManager.
*
* @return double The latitude.
* */
public double getLatitude() {
return _lat;
}
/**
* Retrieve the longitude from the GPSManager.
*
* @return double The longitude.
* */
public double getLongitude() {
return _lon;
}
/**
* Check if the GPSManager has a fix on a location.
*
* @return boolean True if GPSManager has a fix, otherwise false.
* */
public boolean hasFix() {
if(_lat != 0 && _lon != 0)
return true;
else
return false;
}
/**
* Retrieve the accuracy of the fix.
*
* @return float The accuracy.
* */
public float getAccuracy() {
return _accuracy;
}
/**
* Retrieve the last known location.
*
* @return Location The last known location.
* */
public Location getLastLocation() {
return _locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
/**
* <h1>LocationTracker</h1>
*
* <p>Tracks the location for the GPSManager.</p>
* */
private class LocationTracker implements LocationListener {
/** (non-Javadoc)
* @see android.location.LocationListener#onLocationChanged(android.location.Location)
*/
@Override
public void onLocationChanged(Location location) {
_lat = location.getLatitude();
_lon = location.getLongitude();
_accuracy = location.getAccuracy();
}
/** (non-Javadoc)
* @see android.location.LocationListener#onProviderDisabled(java.lang.String)
*/
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "Gps Disabled");
}
/** (non-Javadoc)
* @see android.location.LocationListener#onProviderEnabled(java.lang.String)
*/
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "Gps Enabled");
}
/** (non-Javadoc)
* @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle)
*/
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {};
};
}
我不知道你是想发帖还是想得到。上面的示例使用POST。
我创建了一个MultipartEntity,并向其中添加了两个部分。多部分将以表单的形式发送到服务器,其中POST值的名称为username,而name为username的POST值为new StringBody(_inputName)
对于my WebService类中的post部分:
public void post(String url, MultipartEntity postData) {
HttpClient client = null;
HttpPost post = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
InputStream _inStream = null;
try {
client = new DefaultHttpClient();
post = new HttpPost();
URI uri = URI.create(url);
post.setURI(uri);
post.setEntity(postData);
//Execute the HttpPost request and store the response in httpResponse.
httpResponse = client.execute(post);
//Set the response code from the request's responst.
setResponseCode(httpResponse.getStatusLine().getStatusCode());
//Retrieve the entity from the response.
entity = httpResponse.getEntity();
if(entity != null) {
//Retrieve the content from the entity.
_inStream = entity.getContent();
//Convert the InputStream to String and set the String response to the returned value.
setStringResponse(IOUtility.convertStreamToString(_inStream));
//Close the InputStream.
Log.d(TAG, getStringResponse());
}
//try to create a numeric value of the response result and store it if so
if(GeneralUtil.isNumeric(getStringResponse())) {
setLongResponse(Long.parseLong(getStringResponse()));
}
Log.d(TAG, httpResponse.getStatusLine().getReasonPhrase());
} catch(Exception e) {
e.printStackTrace();
setResponseCode(0);
setLongResponse(0);
setStringResponse("");
} finally {
try {
_inStream.close();
} catch (Exception ignore) {}
}
}
我通过https工作,这更复杂,所以我忽略了这些内容。我在这里要做的是,创建一个新的httpClient和HttpPost,在post中设置URI,将多部分数据添加到post.setEntity()中,然后执行请求并将响应保存在HttpResponse对象中
然后检索实体并将其另存为HttpEntity,以确定从何处获取响应内容。它可以是一个JSON字符串,一个数字,基本上你想要的任何东西。
然后我设置了一些方法,这些方法可以帮助我通过getter和setter轻松检索结果
对于HttpGet,更简单的是,您只需要传递一个url,而不是一个HttpPost对象。您可以创建一个HttpGet对象,向它传递url,_client.execute([HttpGet object]),并以相同的方式检索结果
在php脚本中,您可以直接使用$_POST['username'],它将给出您在上述代码的StringBody中设置的用户名值
对于get,我建议发送一个url(带或不带参数),然后返回一个JSON字符串作为get请求的结果
如果您需要更多帮助,请告诉我。我想这是我能做到的。我无法展示php的一面,因为我使用的是一个自行设计的框架。是的,这正是我想要做的。.我会尝试。.至于客户机-服务器通信,我已经尝试过这个示例,但它不起作用@mprog我无法直接给出代码和指令,但是lin你给出的k有点复杂,我建议你搜索一些类似“android restful”的东西从一个简单的登录页面开始。如果你能做到这一点,你可以做任何其他操作。因为登录通常需要相同的连接,只是结果不同。我希望这能进一步帮助你。祝你好运!如果你有更多问题,请让我知道。尽管有很多restful请求的在线示例。我有尝试了您提到的许多示例,但没有人成功。程序通常在执行http post/get时停止。唯一对我有效的示例是。我必须添加任何jar文件或其他文件吗?(我正在运行wamp(端口80@httpd.conf文件)在eclipse中,我定义了连接url,就好像你在想1.2.3.根据你的经验,关于连接失败的事情,请提一下,thnx
public void post(String url, MultipartEntity postData) {
HttpClient client = null;
HttpPost post = null;
HttpResponse httpResponse = null;
HttpEntity entity = null;
InputStream _inStream = null;
try {
client = new DefaultHttpClient();
post = new HttpPost();
URI uri = URI.create(url);
post.setURI(uri);
post.setEntity(postData);
//Execute the HttpPost request and store the response in httpResponse.
httpResponse = client.execute(post);
//Set the response code from the request's responst.
setResponseCode(httpResponse.getStatusLine().getStatusCode());
//Retrieve the entity from the response.
entity = httpResponse.getEntity();
if(entity != null) {
//Retrieve the content from the entity.
_inStream = entity.getContent();
//Convert the InputStream to String and set the String response to the returned value.
setStringResponse(IOUtility.convertStreamToString(_inStream));
//Close the InputStream.
Log.d(TAG, getStringResponse());
}
//try to create a numeric value of the response result and store it if so
if(GeneralUtil.isNumeric(getStringResponse())) {
setLongResponse(Long.parseLong(getStringResponse()));
}
Log.d(TAG, httpResponse.getStatusLine().getReasonPhrase());
} catch(Exception e) {
e.printStackTrace();
setResponseCode(0);
setLongResponse(0);
setStringResponse("");
} finally {
try {
_inStream.close();
} catch (Exception ignore) {}
}
}