Android 基本活动中的GPS LocationManager和ListenerManager管理
我需要的是, 我的大多数活动都需要用户的位置来获取基于位置的更新数据。因此,我没有在所有活动中单独定义,而是定义了一个基本活动(BaseActivity.java),并声明所有活动都必须继承这个类 例如:Android 基本活动中的GPS LocationManager和ListenerManager管理,android,gps,memory-management,Android,Gps,Memory Management,我需要的是, 我的大多数活动都需要用户的位置来获取基于位置的更新数据。因此,我没有在所有活动中单独定义,而是定义了一个基本活动(BaseActivity.java),并声明所有活动都必须继承这个类 例如: package com.example; import com.example.tools.Utilities; import android.app.Activity; import android.content.BroadcastReceiver; import android.cont
package com.example;
import com.example.tools.Utilities;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.Window;
public class BaseActivity extends Activity {
protected static final String GpsTag = "GPS";
private static LocationManager mLocManager;
private static LocationListener mLocListener;
private static double mDefaultLatitude = 41.0793;
private static double mDefaultLongtitude = 29.0461;
private Location CurrentBestLocation;
private float mMinDistanceForGPSProvider = 200;
private float mMinDistanceForNetworkProvider = 1000;
private float mMinDistanceForPassiveProvider = 3000;
private long mMinTime = 0;
private UserLocation mCurrentLocation = new UserLocation(mDefaultLatitude,
mDefaultLongtitude);
private Boolean showLocationNotification = false;
protected Activity mActivity;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
UserManagement.logOut(getApplication());
Utilities.setApplicationTitle(mActivity);
// finish();
}
};
private BroadcastReceiver mLoggedInReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Utilities.setApplicationTitle(mActivity);
// finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.registerReceiver(mLoggedOutReceiver, new IntentFilter(
Utilities.LOG_OUT_ACTION));
super.registerReceiver(mLoggedInReceiver, new IntentFilter(
Utilities.LOG_IN_ACTION));
mActivity = this;
if (mLocManager == null || mLocListener == null) {
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.i(GpsTag, "Location Changed");
if (isBetterLocation(location, CurrentBestLocation)) {
sendBroadcast(new Intent(
Utilities.LOCATION_CHANGED_ACTION));
mCurrentLocation.Latitude = location.getLatitude();
mCurrentLocation.Longtitude = location.getLongitude();
if (location.hasAccuracy()) {
mCurrentLocation.Accuracy = location.getAccuracy();
}
UserManagement.UserLocation = mCurrentLocation;
mCurrentLocation.Latitude = location.getLatitude();
mCurrentLocation.Longtitude = location.getLongitude();
if (location.hasAccuracy()) {
mCurrentLocation.Accuracy = location.getAccuracy();
}
UserManagement.UserLocation = mCurrentLocation;
CurrentBestLocation = location;
}
}
@Override
public void onProviderDisabled(String provider) {
chooseProviderAndSetLocation();
}
@Override
public void onProviderEnabled(String provider) {
chooseProviderAndSetLocation();
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
chooseProviderAndSetLocation();
}
}
private void chooseProviderAndSetLocation() {
Location loc = null;
if (mLocManager == null)
return;
mLocManager.removeUpdates(mLocListener);
if (mLocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
loc = mLocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else if (mLocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
loc = mLocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
for (String providerName : mLocManager.getProviders(true)) {
float minDistance = mMinDistanceForPassiveProvider;
if (providerName.equals("network"))
minDistance = mMinDistanceForNetworkProvider;
else if (providerName.equals("gps"))
minDistance = mMinDistanceForGPSProvider;
mLocManager.requestLocationUpdates(providerName, mMinTime,
minDistance, mLocListener);
Log.i(GpsTag, providerName + " listener binded...");
}
if (loc != null) {
if (mCurrentLocation == null)
mCurrentLocation = new UserLocation(mDefaultLatitude,
mDefaultLongtitude);
mCurrentLocation.Latitude = loc.getLatitude();
mCurrentLocation.Longtitude = loc.getLongitude();
mCurrentLocation.Accuracy = loc.hasAccuracy() ? loc.getAccuracy()
: 0;
UserManagement.UserLocation = mCurrentLocation;
CurrentBestLocation = loc;
} else {
if (showLocationNotification) {
Utilities
.warnUserWithToast(
getApplication(),
"Default Location");
}
UserManagement.UserLocation = new UserLocation(mDefaultLatitude,
mDefaultLongtitude);
}
}
private static final int TWO_MINUTES = 1000 * 60 * 2;
protected boolean isBetterLocation(Location location,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use
// the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be
// worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same providerl
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return true;
}
return false;
}
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public boolean moveTaskToBack(boolean nonRoot) {
Utilities.warnUserWithToast(getApplicationContext(), "moveTaskToBack: " + nonRoot);
return super.moveTaskToBack(nonRoot);
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocManager.removeUpdates(mLocListener);
super.unregisterReceiver(mLoggedOutReceiver);
super.unregisterReceiver(mLoggedInReceiver);
}
@Override
protected void onRestart() {
super.onRestart();
Utilities.warnUserWithToast(getApplicationContext(), "onRestart: " + getPackageName());
}
@Override
protected void onPause() {
super.onPause();
mLocManager.removeUpdates(mLocListener);
Utilities.warnUserWithToast(getApplicationContext(), "onPause: " + getPackageName());
}
@Override
protected void onResume() {
super.onResume();
Utilities.warnUserWithToast(getApplicationContext(), "onResume: " );
chooseProviderAndSetLocation();
}
@Override
protected void finalize() throws Throwable {
Utilities.warnUserWithToast(getApplicationContext(), "finalize: " );
super.finalize();
}
@Override
protected void onPostResume() {
Utilities.warnUserWithToast(getApplicationContext(), "onPostResume: ");
super.onPostResume();
}
@Override
protected void onStart() {
Utilities.warnUserWithToast(getApplicationContext(), "onStart: " );
super.onStart();
}
@Override
protected void onStop() {
Utilities.warnUserWithToast(getApplicationContext(), "onStop: ");
super.onStop();
}
public void setLocationNotification(Boolean show) {
this.showLocationNotification = show;
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
if (menu != null && UserManagement.CurrentUser != null) {
final MenuItem miExit = menu.add("Log Out");
miExit.setIcon(R.drawable.menu_exit);
miExit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
sendBroadcast(new Intent(Utilities.LOG_OUT_ACTION));
menu.removeItem(miExit.getItemId());
return true;
}
});
}
return super.onCreateOptionsMenu(menu);
}
}
public class MainActivity extends BaseActivity {
}
package.com.example;
导入com.example.tools.Utilities;
导入android.app.Activity;
导入android.content.BroadcastReceiver;
导入android.content.Context;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.location.location;
导入android.location.LocationListener;
导入android.location.LocationManager;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.view.MenuItem.OnMenuItemClickListener;
导入android.view.Window;
公共类BaseActivity扩展了活动{
受保护的静态最终字符串GpsTag=“GPS”;
专用静态位置管理器mLocManager;
私有静态位置侦听器mLocListener;
专用静态双MDEFAULTLATIONE=41.0793;
专用静态双MDEFaultLongtude=29.0461;
私人场所;
专用浮点MMindicationPergpProvider=200;
私有float mmindistanefornetworkprovider=1000;
私有浮点MMindicationPerPassiveProvider=3000;
私有长时间mm=0;
private UserLocation mCurrentLocation=新用户位置(mDefaultLatitude,
(长期性);
私有布尔值showLocationNotification=false;
保护活性;
专用BroadcastReceiver mLoggedOutReceiver=新的BroadcastReceiver(){
@凌驾
公共void onReceive(上下文、意图){
UserManagement.logOut(getApplication());
实用程序.setApplicationTitle(mActivity);
//完成();
}
};
private BroadcastReceiver mLoggedInReceiver=新的BroadcastReceiver(){
@凌驾
公共void onReceive(上下文、意图){
实用程序.setApplicationTitle(mActivity);
//完成();
}
};
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(窗口。功能\u无\u标题);
超级注册表接收器(MLOGGEDOUTRECEVIVER,新的意向过滤器(
实用程序。注销操作);
超级注册表接收器(MLOGGEDIRECEIVER,新的IntentFilter(
实用程序。登录(操作);
mActivity=这个;
如果(mLocManager==null | | mLocListener==null){
mLocManager=(LocationManager)getSystemService(Context.LOCATION\u服务);
mLocListener=新位置Listener(){
@凌驾
已更改位置上的公共无效(位置){
Log.i(GpsTag,“位置变更”);
if(isBetterLocation(location,CurrentBestLocation)){
发送广播(新意图)(
公用设施。位置(更改(操作));
mCurrentLocation.Latitude=location.getLatitude();
mCurrentLocation.longtudent=location.getLongitude();
if(location.hasAccurance()){
mCurrentLocation.accurity=location.getaccurity();
}
UserManagement.UserLocation=mCurrentLocation;
mCurrentLocation.Latitude=location.getLatitude();
mCurrentLocation.longtudent=location.getLongitude();
if(location.hasAccurance()){
mCurrentLocation.accurity=location.getaccurity();
}
UserManagement.UserLocation=mCurrentLocation;
CurrentBestLocation=位置;
}
}
@凌驾
公共无效onProviderDisabled(字符串提供程序){
选择ProviderAndSetLocation();
}
@凌驾
公共无效onProviderEnabled(字符串提供程序){
选择ProviderAndSetLocation();
}
@凌驾
public void onStatusChanged(字符串提供程序,int状态,
捆绑(附加){
}
};
选择ProviderAndSetLocation();
}
}
私有void选择ProviderAndSetLocation(){
位置loc=空;
if(mLocManager==null)
返回;
mLocManager.removeUpdates(mLocListener);
if(mLocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
loc=mLocManager
.getLastKnownLocation(LocationManager.网络提供商);
}else if(mLocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
loc=mLocManager
.getLastKnownLocation(LocationManager.GPS\U提供商);
}
对于(字符串提供程序名称:mLocManager.getProviders(true)){
float minDistance=mMinDistanceForPassiveProvider;
if(providerName.equals(“网络”))
minDistance=mIndiencePhoneNetworkProvider;
else if(providerName.equals(“gps”))
minDistance=mIndienceForgpProvider;
mLocManager.requestLocationUpdates(提供程序名称、mMinTime、,
思维距离,mLocListener);
Log.i(GpsTag,providerName+“侦听器绑定…”);
}
如果(loc!=null){
if(mCurrentLocation==null)
mCurrentLocation=新用户位置(mDefaultLatitude,
(长期性);
mCurrentLocation.Latitude=loc.getLatitude();
McCurrentLocation。
@Override
public void onDestroy() {
// ending logic.
}
package com.test.examppplee;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class LocationService extends Service{
@Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "onCreate", Toast.LENGTH_LONG).show();
super.onCreate();
}
@Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "onDestroy", Toast.LENGTH_LONG).show();
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(getApplicationContext(), "onStart", Toast.LENGTH_LONG).show();
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
package com.test.examppplee;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(getApplicationContext(), LocationService.class));
}
public void finish(View v){
finish();
}
public void start(View v){
startActivity(new Intent(getApplicationContext(), ServiceTestActivity.class));
}
}
package com.test.examppplee;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class ServiceTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void finish(View v){
finish();
}
public void start(View v){
startActivity(new Intent(getApplicationContext(), ServiceTestActivity2.class));
}
}