【问题标题】:Android: location; activity and service安卓:位置;活动与服务
【发布时间】:2011-07-06 06:36:58
【问题描述】:

我正在开发一些应用程序,该应用程序应该获取当前位置,并且在设备位于某个半径后应该向应用程序显示一些消息。 我有几个问题。 我正在尝试使用

获取位置
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000*60*5, 50, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000*60*5, 50, locationListener);
addProximityAlert(LAT,LONG);

private void addProximityAlert(double latitude, double longitude) 
        {
            Intent intent = new Intent(this.getApplicationContext(), SOME_CLASS_HERE); 
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //Does this needed even if apllication/activity is alive?
            PendingIntent proximityIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK); //and does this needed again?
            locationManager.addProximityAlert(latitude, longitude, Radius, 0, proximityIntent);
        }
  1. 如果我使用 requestLocationUpdates,那么 GPS 始终工作。这是对电池的浪费。也许有一些方法,例如,暂停几分钟?我的意思是每 5 分钟使用一次 GPS,例如从一个位置获取到下一个位置。如何实现?

  2. 如果 SOME_CLASS_HERE - 某个活动类,那么我怎么知道这个事件是否准确地调用了它?因为当 ProximityAlert 被触发时,我还需要调用一些活动的函数。我该怎么做?


UPD:现在我只使用 Activity(我根本没有 Service) 我正在尝试下一步:

Intent intent = new Intent(getString(R.string.intent_message_location_fetched));
PendingIntent proximityIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
locationManager.addProximityAlert(LAT, LONG, RADIUS, 0, proximityIntent);

据我了解,操作 R.string.intent_message_location_fetched 的意图应该在位置大约 LAT LONG 后触发。

然后我正在尝试创建 BroadcastReciver 类:

public class MyBroadcastReciver extends BroadcastReceiver {
    MyActivity mainActivity;
    public MyBroadcastReciver(MyActivity activity)
    {
        mainActivity = activity;
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        mainActivity.ShowToast("Recived : " + intent.getAction());
    }
}

并在 MyActivity 类中注册接收者:

public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        myReciver = new MyBroadcastReciver(this);
        IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(getString(R.string.intent_message_location_fetched));
        registerReceiver(myReciver, intentFilter);
...

但是当我在 LAT LONG 位置时,什么也没有发生。怎么了? 也许我应该在 AndroidManifest.xml 中注册接收器?但具体如何?

【问题讨论】:

    标签: java android geolocation


    【解决方案1】:

    1.您应该在此处查看答案以使用计时器打开/关闭通过 GPS 进行的位置查找:android locationManager requestLocationUpdates

    它将每 X 秒启动一个计时器。在计时器的处理过程中,将请求位置更新,在检索到位置后,它将停止 GPS 侦听器。

    2.您应该在接近警报逻辑结束后发送意图。然后,您可以注册一个侦听该意图的广播接收器,并进行处理。 Intent 机制提供了一种在活动/服务之间进行通信的松散耦合方式。

    您可以找到an example,了解如何将意图广播(在您的情况下是从您的接近警报中)到广播接收器(您的应用程序中的一个新组件,它将接收该意图并相应地处理它)。它还展示了如何在清单中设置接收器以侦听您的自定义 Intent。

    【讨论】:

      【解决方案2】:

      如果我使用 requestLocationUpdates,那么 GPS 始终可以工作。这是对电池的浪费。也许有一些方法,例如,暂停几分钟?我的意思是每 5 分钟使用一次 GPS,例如从一个位置获取到下一个位置。如何实现这一点?

      addProximityAlert() 每 4 分钟使用一次 GPS。如果您想每 x 分钟使用一次 GPS,请运行服务并每 x 分钟获取一次single shot fixes,然后手动检查该区域周围是否存在它。

      如果 SOME_CLASS_HERE - 一些活动 课,那我怎么知道 这个事件到底叫什么?因为 当 ProximityAlert 被触发时我 需要调用一些活动的功能 也是。我怎么能这样做?

      不完全确定你在这里问什么

      这里是如何使用挂起的意图

          PendingIntent pendingIntent;
          Intent intent = new Intent();
          intent.setClass(mContext, yourActivity.class);
          pendingIntent =  PendingIntent.getActivity(mContext, 0, intent, 0);
      

      FLAG_ACTIVITY_NEW_TASK : 这使得启动的活动成为任务的根活动。如果您正在启动的 Activity 的任务已经在运行,那么新的 Activity 将不会启动;相反,当前任务将简单地以其上次所处的状态被带到屏幕的前面。

      【讨论】:

        【解决方案3】:

        我正在使用此代码获取用户的当前位置。

         public class HomeActivity extends Activity implements LocationListener{
        public static Context mContext;
        private double latitude, longitude;
         public LocationManager mLocManager;
        // *******This is the new Code start on 11/4/2011 at 3 o'clock
        
        
        /**
         * This is the Home Button if user Login then it is move to TennisAppActivity otherwise move to Login  
         *
         */
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            mContext=this;
            super.onCreate(savedInstanceState);
            setContentView(R.layout.homelayout);
            
        
            mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
             
            mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    this);
            mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
                    0, this);
            locationUpdate();
            ((Button) this.findViewById(R.id.ButtonHome))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View arg0) {
                            
                                startActivity(new Intent(HomeActivity.this,
                                        DefaultDisplay.class));
                            
                        }
                    });
        
            ((Button) this.findViewById(R.id.ButtonProfile))
                    .setOnClickListener(new OnClickListener() {
        
                        public void onClick(View arg0) {
                            if (GUIStatics.boolLoginStatus) {
                                startActivity(new Intent(HomeActivity.this,
                                        MyProfile.class));
                            } else {
                                Intent intent=new Intent(HomeActivity.this,
                                        Login.class);
                                intent.putExtra("moveTo","MyProfile");
                                startActivity(intent);
                            }
                        }
                    });
        
            ((Button) this.findViewById(R.id.ButtonNotifications))
                    .setOnClickListener(new OnClickListener() {
        
                        public void onClick(View arg0) {
                            if (GUIStatics.boolLoginStatus) {
                                startActivity(new Intent(HomeActivity.this,
                                        ShowAllNotificationActiviry.class));
                            } else {
                                Intent intent=new Intent(HomeActivity.this,
                                        Login.class);
                                intent.putExtra("moveTo","ShowAllNotificationActiviry");
                                startActivity(intent);
                            }
                        }
                    });
        
            ((Button) this.findViewById(R.id.ButtonFavorites))
                    .setOnClickListener(new OnClickListener() {
        
                        public void onClick(View arg0) {
                            if (GUIStatics.boolLoginStatus) {
                                startActivity(new Intent(HomeActivity.this,
                                        FavoritesActivity.class));
                            } else {
                                Intent intent=new Intent(HomeActivity.this,
                                        Login.class);
                                intent.putExtra("moveTo","FavoritesActivity");
                                startActivity(intent);
                            }
                        }
                    });
        
                    ((Button) this.findViewById(R.id.ButtonMore))
                    .setOnClickListener(new OnClickListener() {
                        public void onClick(View arg0) {
                                startActivity(new Intent(HomeActivity.this,
                                        MoreListActivity.class));
                        }
                    });
        
        }
        
        public void locationUpdate()
        {
            CellLocation.requestLocationUpdate();
        }
        
        
        public void getAddress(double lat, double lng) {
            Geocoder geocoder = new Geocoder(HomeActivity.mContext, Locale.getDefault());
            try {
                List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
                Address obj = addresses.get(0);
                String add = obj.getAddressLine(0);
                GUIStatics.currentAddress = obj.getSubAdminArea() + ","
                        + obj.getAdminArea();
                GUIStatics.latitude = obj.getLatitude();
                GUIStatics.longitude = obj.getLongitude();
                GUIStatics.currentCity= obj.getSubAdminArea();
                GUIStatics.currentState= obj.getAdminArea();
                add = add + "\n" + obj.getCountryName();
                add = add + "\n" + obj.getCountryCode();
                add = add + "\n" + obj.getAdminArea();
                add = add + "\n" + obj.getPostalCode();
                add = add + "\n" + obj.getSubAdminArea();
                add = add + "\n" + obj.getLocality();
                add = add + "\n" + obj.getSubThoroughfare();
        
                Log.v("IGA", "Address" + add);
                // Toast.makeText(this, "Address=>" + add,
                // Toast.LENGTH_SHORT).show();
        
                // TennisAppActivity.showDialog(add);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
        
        
        
        public void onLocationChanged(Location location) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            GUIStatics.latitude=location.getLatitude();
            GUIStatics.longitude= location.getLongitude();
            Log.v("Test", "IGA" + "Lat" + latitude + "   Lng" + longitude);
            //mLocManager.r
             
            getAddress(latitude, longitude);
            if(location!=null)
            {
                
            mLocManager.removeUpdates(this);
            }
            // Toast.makeText(this, "Lat" + latitude + "   Lng" + longitude,
            // Toast.LENGTH_SHORT).show();
        }
        
        
        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub
            Toast.makeText(HomeActivity.this, "Gps Disabled", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(
                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
        
        
        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub
            
        }
        
        
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
             if(arg1 == 
                    LocationProvider.TEMPORARILY_UNAVAILABLE) { 
                                            Toast.makeText(HomeActivity.this, 
                    "LocationProvider.TEMPORARILY_UNAVAILABLE", 
                    Toast.LENGTH_SHORT).show(); 
                                } 
                                else if(arg1== LocationProvider.OUT_OF_SERVICE) { 
                                            Toast.makeText(HomeActivity.this, 
                    "LocationProvider.OUT_OF_SERVICE", Toast.LENGTH_SHORT).show(); 
                                } 
            
        }
        

        }

        在这段代码中你可以找到

        mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, 这个);

        该方法第一个参数是provide,II-timeforupdate location,IIImindistance for update request,

         mLocManager.removeUpdates(this);
        

        上述调用方法在获取位置时删除位置更新,从而节省电池。

        【讨论】:

          猜你喜欢
          • 2014-09-29
          • 1970-01-01
          • 2015-10-03
          • 1970-01-01
          • 2018-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多