android - 在广播接收器中发送位置

标签 android location broadcastreceiver sms

我想通过来自广播接收器的短信发送位置信息。该代码根本无法确定我的位置。谁能帮我解决我的问题?

SmsRemoteController

public class SmsRemoteController extends BroadcastReceiver {
    private static final int MODE_WORLD_READABLE = 1;
    private String smsFirstCode;
    private SharedPreferences myPrefs;
    private Context contexts;
    private String sendingNumber = "";


    @Override
    public void onReceive(Context context, Intent intent) {
        contexts = context;
        myPrefs = context.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        String smsMode = myPrefs.getString("state", "not");
        AppLocationService appLocationService;
        appLocationService = new AppLocationService(SmsRemoteController.class);

        if (smsMode.equals("ON")) {

            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            String smsBody = "";
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                msgs = new SmsMessage[pdus.length];
                for (int i = 0; i < pdus.length; i++) {
                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    sendingNumber += msgs[i].getOriginatingAddress();
                    smsBody = msgs[i].getMessageBody().toString();
                }

                // Toast.makeText(contexts, "number"+sendingNumber+"..body"+smsBody.toLowerCase(), Toast.LENGTH_SHORT).show();


                if (smsBody.equals("locate")) {


                    Location nwLocation = appLocationService.getLocation(LocationManager.NETWORK_PROVIDER);

                    if (nwLocation != null) {
                        double latitude = nwLocation.getLatitude();
                        double longitude = nwLocation.getLongitude();
                        Toast.makeText(contexts, "Mobile Location (NW): \nLatitude: " + latitude + "\nLongitude: " + longitude,
                                Toast.LENGTH_LONG).show();

                    } else {
                        Location gpsLocation = appLocationService.getLocation(LocationManager.GPS_PROVIDER);

                        if (gpsLocation != null) {
                            double latitude = gpsLocation.getLatitude();
                            double longitude = gpsLocation.getLongitude();
                            Toast.makeText(contexts, "Mobile Location (GPS): \nLatitude: " + latitude
                                            + "\nLongitude: " + longitude,
                                    Toast.LENGTH_LONG).show();
                        }

                    }


                }
                //abortBroadcast();
            }// end of onReceive()


        }

    } // end of the class
}

AppLocationService

public class AppLocationService extends Service implements LocationListener {

    protected LocationManager locationManager;
    Location location;

    private static final long MIN_DISTANCE_FOR_UPDATE = 10;
    private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;

    public AppLocationService(Context context) {
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
    }

    public Location getLocation(String provider) {
        if (locationManager.isProviderEnabled(provider)) {
            locationManager.requestLocationUpdates(provider,MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
            if (locationManager != null) {
                location = locationManager.getLastKnownLocation(provider);
                return location;
            }
        }
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}

最佳答案

您调用服务的方式不是使用服务的首选方式,我们从不在 BoradcastReceiver 中创建服务对象,因此您可以注册一个位置接收器,并根据您收到的更新值显示需要执行的 Toast手术。 我已经在下面更新了满足您要求的一种可能的解决方案。

此外,我仍然更愿意从广播接收器启动服务以获取位置,因为我们不应该对广播接收器进行大量操作,

public class SmsRemoteController extends BroadcastReceiver {
    private static final int MODE_WORLD_READABLE = 1;
    private String smsFirstCode;
    private SharedPreferences myPrefs;
    private Context contexts;
    private String sendingNumber = "";
    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 Context _context;
    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();
            } catch (Exception e) {
            }
        }
    };


    @Override
    public void onReceive(Context context, Intent intent) {
        contexts = context;
        myPrefs = context.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
        String smsMode = myPrefs.getString("state", "not");

        if (smsMode.equals("ON")) {

            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            String smsBody = "";
            if (bundle != null) {
                Object[] pdus = (Object[]) bundle.get("pdus");
                msgs = new SmsMessage[pdus.length];
                for (int i = 0; i < pdus.length; i++) {
                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    sendingNumber += msgs[i].getOriginatingAddress();
                    smsBody = msgs[i].getMessageBody().toString();
                }

                // Toast.makeText(contexts,
                // "number"+sendingNumber+"..body"+smsBody.toLowerCase(),
                // Toast.LENGTH_SHORT).show();

                if (smsBody.equals("locate")) {

                    _context = context;
                    locationManager = (LocationManager) context
                            .getSystemService(Context.LOCATION_SERVICE);
                    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                                MIN_TIME_REQUEST, 5, locationListener);
                        Location gotLoc = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        double latitude = gotLoc.getLatitude();
                        double longitude = gotLoc.getLongitude();
                        Toast.makeText(contexts, "Mobile Location (NW): \nLatitude: " + latitude + "\nLongitude: " + longitude,
                                Toast.LENGTH_LONG).show();
                    } 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);
                    }
                }
                // abortBroadcast();
            }// end of onReceive()

        }

    } // end of the class
}

关于android - 在广播接收器中发送位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34012215/

相关文章:

Android - 带有包含 fragment 的布局的 DialogFragment

android - 如何减小 Android Studio 的项目文件夹大小

android - 在当前 android fragment 中禁用 ScreenShot

android - 设置 GPS 位置的 'expiry' 时间

android - 如何在安装和卸载应用程序期间接收广播接收器?

android - 一项并发服务或多项服务

android - 在 Ubuntu 上设置 Android 主目录。这是多余的吗?

使用播放服务位置 api 启用的 android 检查位置服务

android - 如何在 map 初始化之前询问是否启用了位置?

android - NotificationManager.cancel(id) 在广播接收器中不起作用