Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 获取广播接收器中的GPS位置/或广播接收器数据传输服务_Android_Service_Broadcastreceiver - Fatal编程技术网

Android 获取广播接收器中的GPS位置/或广播接收器数据传输服务

Android 获取广播接收器中的GPS位置/或广播接收器数据传输服务,android,service,broadcastreceiver,Android,Service,Broadcastreceiver,我是android新手。 我想在广播接收器中获取GPS位置,但它显示错误 我的代码是: public void onReceive(Context context, Intent intent) { LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // errors in getSystemService method

我是android新手。
我想在广播接收器中获取GPS位置,但它显示错误

我的代码是:

public void onReceive(Context context, Intent intent) {
    LocationManager locManager = (LocationManager) 
            getSystemService(Context.LOCATION_SERVICE);
    // errors in getSystemService method
    LocationListener locListener = new MyLocationListener();
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            locListener);
    Location loc = locManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Log.d(" **location**", " location" + loc.getLatitude());
}
问题:

  • 是否可以在广播接收机中获取GPS位置数据
  • 到目前为止,我尝试的另一种方法是使用广播接收器调用的服务。该服务可以获取GPS数据,但如何在广播接收器中获取

  • 是的,两者都有可能

    您的服务带有计时器,可在以下时间段内向位置接收器发送请求:

    public class SrvPositioning extends Service {
    
        // An alarm for rising in special times to fire the
        // pendingIntentPositioning
        private AlarmManager alarmManagerPositioning;
        // A PendingIntent for calling a receiver in special times
        public PendingIntent pendingIntentPositioning;
    
        @Override
        public void onCreate() {
            super.onCreate();
            alarmManagerPositioning = (AlarmManager) 
                    getSystemService(Context.ALARM_SERVICE);
            Intent intentToFire = new Intent(
                    ReceiverPositioningAlarm.ACTION_REFRESH_SCHEDULE_ALARM);
            intentToFire.putExtra(ReceiverPositioningAlarm.COMMAND,
                    ReceiverPositioningAlarm.SENDER_SRV_POSITIONING);
            pendingIntentPositioning = PendingIntent.getBroadcast(this, 0,
                    intentToFire, 0);
        };
    
        @Override
        public void onStart(Intent intent, int startId) {
            try {
                long interval = 60 * 1000;
                int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
                long timetoRefresh = SystemClock.elapsedRealtime();
                alarmManagerPositioning.setInexactRepeating(alarmType,
                        timetoRefresh, interval, pendingIntentPositioning);
            } catch (NumberFormatException e) {
                Toast.makeText(this,
                        "error running service: " + e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(this,
                        "error running service: " + e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        }
    
        @Override
        public IBinder onBind(Intent arg0) {
            return null;
        }
    
        @Override
        public void onDestroy() {
            this.alarmManagerPositioning.cancel(pendingIntentPositioning);
            ReceiverPositioningAlarm.stopLocationListener();
        }
    }
    
    你的接受者有一个听众。监听器可用于您的活动中,以通知您新位置已准备就绪:

    public class ReceiverPositioningAlarm extends BroadcastReceiver {
    
        public static final String COMMAND = "SENDER";
        public static final int SENDER_ACT_DOCUMENT = 0;
        public static final int SENDER_SRV_POSITIONING = 1;
        public static final int MIN_TIME_REQUEST = 5 * 1000;
        public static final String ACTION_REFRESH_SCHEDULE_ALARM =
                        "org.mabna.order.ACTION_REFRESH_SCHEDULE_ALARM";
        private static Location currentLocation;
        private static Location prevLocation;
        private static Context _context;
        private String provider = LocationManager.GPS_PROVIDER;
        private static Intent _intent;
        private static LocationManager locationManager;
        private static LocationListener locationListener = new LocationListener() {
    
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras){
                try {
                    String strStatus = "";
                    switch (status) {
                    case GpsStatus.GPS_EVENT_FIRST_FIX:
                        strStatus = "GPS_EVENT_FIRST_FIX";
                        break;
                    case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                        strStatus = "GPS_EVENT_SATELLITE_STATUS";
                        break;
                    case GpsStatus.GPS_EVENT_STARTED:
                        strStatus = "GPS_EVENT_STARTED";
                        break;
                    case GpsStatus.GPS_EVENT_STOPPED:
                        strStatus = "GPS_EVENT_STOPPED";
                        break;
                    default:
                        strStatus = String.valueOf(status);
                        break;
                    }
                    Toast.makeText(_context, "Status: " + strStatus,
                            Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            @Override
            public void onProviderEnabled(String provider) {}
    
            @Override
            public void onProviderDisabled(String provider) {}
    
            @Override
            public void onLocationChanged(Location location) {
                try {
                    Toast.makeText(_context, "***new location***",
                            Toast.LENGTH_SHORT).show();
                    gotLocation(location);
                } catch (Exception e) {
                }
            }
        };
    
        // received request from the calling service
        @Override
        public void onReceive(final Context context, Intent intent) {
            Toast.makeText(context, "new request received by receiver",
                    Toast.LENGTH_SHORT).show();
            _context = context;
            _intent = intent;
            locationManager = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);
            if (locationManager.isProviderEnabled(provider)) {
                locationManager.requestLocationUpdates(provider,
                        MIN_TIME_REQUEST, 5, locationListener);
                Location gotLoc = locationManager
                        .getLastKnownLocation(provider);
                gotLocation(gotLoc);
            } else {
                Toast t = Toast.makeText(context, "please turn on GPS",
                        Toast.LENGTH_LONG);
                t.setGravity(Gravity.CENTER, 0, 0);
                t.show();
                Intent settinsIntent = new Intent(
                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                settinsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                _context.startActivity(settinsIntent);
            }
        }
    
        private static void gotLocation(Location location) {
            prevLocation = currentLocation == null ? null : new Location(
                    currentLocation);
            currentLocation = location;
            if (isLocationNew()) {
                OnNewLocationReceived(location);
                Toast.makeText(_context, "new location saved",
                        Toast.LENGTH_SHORT).show();
                stopLocationListener();
            }
        }
    
        private static boolean isLocationNew() {
            if (currentLocation == null) {
                return false;
            } else if (prevLocation == null) {
                return true;
            } else if (currentLocation.getTime() == prevLocation.getTime()) {
                return false;
            } else {
                return true;
            }
        }
    
        public static void stopLocationListener() {
            locationManager.removeUpdates(locationListener);
            Toast.makeText(_context, "provider stoped", Toast.LENGTH_SHORT)
                    .show();
        }
    
        // listener ----------------------------------------------------
        static ArrayList<OnNewLocationListener> arrOnNewLocationListener = 
                new ArrayList<OnNewLocationListener>();
    
        // Allows the user to set a OnNewLocationListener outside of this class
        // and react to the event.
        // A sample is provided in ActDocument.java in method: startStopTryGetPoint
        public static void setOnNewLocationListener(
                OnNewLocationListener listener) {
            arrOnNewLocationListener.add(listener);
        }
    
        public static void clearOnNewLocationListener(
                OnNewLocationListener listener) {
            arrOnNewLocationListener.remove(listener);
        }
    
        // This function is called after the new point received
        private static void OnNewLocationReceived(Location location) {
            // Check if the Listener was set, otherwise we'll get an Exception
            // when we try to call it
            if (arrOnNewLocationListener != null) {
                // Only trigger the event, when we have any listener
                for (int i = arrOnNewLocationListener.size() - 1; i >= 0; i--) {
                    arrOnNewLocationListener.get(i).onNewLocationReceived(
                            location);
                }
            }
        }
    }
    
    在您仅获得一分的活动中:

    protected void btnGetPoint_onClick() {
        Intent intentToFire = new Intent(
                ReceiverPositioningAlarm.ACTION_REFRESH_SCHEDULE_ALARM);
        intentToFire.putExtra(ReceiverPositioningAlarm.COMMAND,
                ReceiverPositioningAlarm.SENDER_ACT_DOCUMENT);
        sendBroadcast(intentToFire);
        OnNewLocationListener onNewLocationListener = new OnNewLocationListener() {
    
            @Override
            public void onNewLocationReceived(Location location) {
                // use your new location here then stop listening
                ReceiverPositioningAlarm.clearOnNewLocationListener(this);
            }
        };
        // start listening for new location
        ReceiverPositioningAlarm
                .setOnNewLocationListener(onNewLocationListener);
    }
    
    编辑:

    如果要在活动中启动服务:

    this.startService(new Intent(this, SrvPositioning.class));
    
    类似地,您可以在服务中定义一个侦听器来接收接收方找到的位置

    编辑

    在清单中添加以下行

    <service
                android:name="org.mabna.order.services.SrvPositioning"
                android:enabled="true" />
    
    <receiver android:name="org.mabna.order.receivers.ReceiverPositioningAlarm" >
    
                <!-- this Broadcast Receiver only listens to the following intent -->
                <intent-filter>
                    <action android:name="org.mabna.order.ACTION_REFRESH_SCHEDULE_ALARM" />
                </intent-filter>
            </receiver>
    

    从BroadcastReceiver我也无法启动Location Manager。所以我在BroadcastReceiver上启动了一个服务,在这个服务中我操纵了LocationManager。我想我在Android开发文档中找到了这个解决方案。您还可以启动活动而不是服务

    以下是BroadcastReceiver上切换到服务的代码:

    将其写入
    onReceive
    方法中

        Intent serviceIntent = new Intent(context,MyService.class);
        serviceIntent.putExtra("locateRequest", "locateRequest"); // if you want pass parameter from here to service
        serviceIntent.putExtra("queryDeviceNumber", results[1]);
        context.startService(serviceIntent); //start service for get location
    
    第1步: 打开AndroidManifest.xml
    并添加广播接收器

    <receiver
            android:name=".Util.GpsConnectorReceiver"
            android:enabled="true">
            <intent-filter>
                <!-- Intent filters for broadcast receiver -->
                 <action android:name="android.location.PROVIDERS_CHANGED" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>`
    
    步骤4:创建另一个名为ConnectivityCheck的服务类

    public class ConnectivityCheck extends Service {
    
    @Override
    public void onCreate() {
        super.onCreate();
        if (!checkConnection()) {
            Toast.makeText(context, "off", Toast.LENGTH_LONG).show();
            Intent dialogIntent = new Intent(this, ActivityDialogInternet.class);
            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(dialogIntent);
        }
        stopSelf();
    }
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    private boolean checkConnection() {
         final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    
    }}
    
    步骤5:创建一个名为ActivityDialogGps的活动

    public class ActivityDialogGps extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_gps);
    }}
    

    第6步:当Gps连接关闭时,调用活动对话框Gps
    并显示对话框:

    只是想知道,您是否测量了这种方法(1分钟更新)消耗的电池量,以及您是否有始终处于活动状态的LocationListener(不是针对Gps而是针对网络).非常感谢。还有一个问题..如果我没有从任何活动启动服务,那么服务会在给定的时间或距离限制后自动启动吗?我认为您必须在活动中启动服务。搜索:)请再告诉我一件事……你说的“在你的活动中只得到一分”是什么意思:“…?!”。。。?!?第四个编码块的标题…在活动中写入该代码,以从侦听器中获得一分。它是关于使用侦听器的。
    public class GpsConnectorReceiver extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent intent) {
    
       if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
            Intent pushIntent = new Intent(context, ConnectivityCheck .class);
                    context.startService(pushIntent);
        }
    }}
    
    public class ConnectivityCheck extends Service {
    
    @Override
    public void onCreate() {
        super.onCreate();
        if (!checkConnection()) {
            Toast.makeText(context, "off", Toast.LENGTH_LONG).show();
            Intent dialogIntent = new Intent(this, ActivityDialogInternet.class);
            dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(dialogIntent);
        }
        stopSelf();
    }
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    private boolean checkConnection() {
         final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    
    }}
    
    public class ActivityDialogGps extends AppCompatActivity {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog_gps);
    }}