我正在构建一个客户端服务器安卓应用,它与商店和我想要的(当用户接近2或3个商店及其数据库在线时)我的应用到了解他可以连接到其中一个商店的数据库并将它们列在屏幕上。 (当我们想要连接到互联网时,可用的wif就会发生什么)
我怎样才能做到这一点?
我希望我说清楚我在找什么。
答案 0 :(得分:0)
如果我错了,请纠正我。您正在编写一个应用程序,可以从服务器访问数据,服务器/数据库属于商店吗?
如果我对您的问题的理解是正确的,请执行以下操作:
我个人会使用JSON来处理来自客户端的请求< - >服务器。因为它重量轻,易于使用。
撰写广播公司:BraodcastReciever
示例:
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());
}
};
我没有发布整个代码。我在ConnectivityBroadcastReceiver周围写了一个包装器。但是使用给定的代码,你应该能够得到足够的。注意代码状态是一个包含3个值的枚举:CONNECTED,NOT_CONNECTED,UNKNOWN
至于GPS经理:
/**
* <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) {};
};
}
根据您自己的需要扩展它。 gps管理器中的大多数代码都是不言自明的。
对于其余的东西,有很多不同的方法,你必须自己看看。
作为对您评论的回答,我将向您展示我对webrequest的实施。 我个人使用apache-mime4j-0.6.jar和httpmime-4.0.1.jar。
WebService _service = new WebService();
@Override
protected String doInBackground(String... arg0) {
try {
MultipartEntity multipart = new MultipartEntity();
multipart.addPart("username", new StringBody(_inputName));
multipart.addPart("password", new StringBody(_inputPass));
_service.post(QfConfig.RESTFUL_LOGIN_URL, multipart);
long response = _service.getLongResponse();
if(response != 0) {
_pgUserId = response;
_onlineValidated = true;
}
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
我不知道你想要POST或GET。上面的例子使用POST。 我创建了一个MultipartEntity,并添加了两个部分。 multipart将作为POST值的名称为username的表单发送到服务器,名称为username的帖子的VALUE是新的StringBody(_inputName)。
对于我的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,如果帖子设置URI,将多部分数据添加到post.setEntity()然后执行请求并将响应保存在HttpResponse对象中。
然后我检索实体并将其保存为HttpEntity,以及我从何处获取响应内容。哪个可以是JSON字符串,一个数字,基本上你想要什么。 然后我设置了一些方法,可以帮助我轻松地通过getter和setter检索结果。
对于HttpGet它更容易,你只需要传递一个url,而不是你创建一个HttpGet对象的HttpPost对象,传递它的url,_client.execute([HttpGet对象])并以同样的方式检索结果
在php脚本中,你可以直接使用$ _POST ['username'],它会在上面的代码中给出你在StringBody中设置的用户名的值。
使用get,我会建议发送一个url(有或没有params,然后将结果发送回get请求。
如果您需要更多帮助,请告诉我。我认为这是我能走的尽可能的。我无法展示php方面因为我使用了自己设计的框架。