类型MainActivity没有外围实例是在范围访问 [英] No enclosing instance of the type MainActivity is accessible in scope

查看:389
本文介绍了类型MainActivity没有外围实例是在范围访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code,这是我希望得到的 GPS GPSTracker 经纬度类
但错误显示

  GPS =新GPSTracker(MainActivity.this);
            gps.getLatitude();

类型MainActivity没有外围实例是在范围访问

完整code
BootComplete.java

 公共类BootComplete扩展广播接收器{//私有静态最后弦乐preFS_NAME = NULL;
公共静态最后弦乐preFS_NAME =我的preFS
串storedSimSerial;
串currentSimSerial;
字符串电子邮件; //用户的电子邮件地址输入,生成电子邮件,发送到这个地址,
串mobileno; //用户的手机号码输入,产生的短信发送到这个地址
串短信; //生成短信到用户
公共GPSTracker GPS;
@覆盖
公共无效的onReceive(最终上下文的背景下,意图意图){    共享preferences preFS = context.getShared preferences(preFS_NAME,0);
    storedSimSerial = prefs.getString(storedSimSerial,);
    mobileno = prefs.getString(trustedNum,);
    电子邮件= prefs.getString(电子邮件,);
    TelephonyManager TM =(TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
    currentSimSerial = tm.getSimSerialNumber();    如果(currentSimSerial!= NULL){
        如果(currentSimSerial.compareToIgnoreCase(storedSimSerial)== 0){        }其他{            。preFS = context.getApplicationContext()getShared preferences(preFS_NAME,0);
            共享preferences.Editor编辑器= prefs.edit();            GPS =新GPSTracker(MainActivity.this);
            gps.getLatitude();            短信=警告!\\ NSIM卡改变\\ NSIM序列号:\\ n+ tm.getSimSerialNumber()+
                    \\ n网络:+ tm.getNetworkOperatorName()+\\ nLatitude:\\ n+ gps.getLatitude();            editor.putBoolean(SimChangeMail,真正的);
            editor.putString(subjectSimChange,您的SIM卡已经改变了。);
            editor.putString(bodySimChange,辛序列号为:\\ n+ tm.getSimSerialNumber()+\\ n+
                    这辛序列号是唯一的,用于识别所有者\\ n网络操作员是:+
                    tm.getNetworkOperatorName()+
                    \\ nThanks使用移动安全应用程序);
            editor.putString(SimChangeSms,短信);
            editor.commit();            SmsManager SM = SmsManager.getDefault();
            字符串NUM = mobileno;
            sm.sendTextMessage(NUM,空,短信,NULL,NULL);
        }
    }其他{    }
}
}

GPSTracker.java

 公共类GPSTracker扩展服务实现LocationListener的{    私人最终上下文mContext;    //标志GPS状态
    布尔isGPSEnabled = FALSE;    //标志网络状态
    布尔isNetworkEnabled = FALSE;    //标志GPS状态
    布尔canGetLocation = FALSE;    地点位置; // 位置
    双纬度; //纬度
    双经度; //经度    //最小距离改变米的更新
    私有静态最后长MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10米    //毫秒更新之间的最短时间
    私有静态最后长MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟    //声明一个位置管理
    受保护的LocationManager的LocationManager;    公共GPSTracker(上下文的背景下){
        this.mContext =背景;
        的getLocation();
    }    公共场所的getLocation(){
        尝试{
            的LocationManager =(的LocationManager)mContext
                    .getSystemService(LOCATION_SERVICE);            //获取GPS状态
            isGPSEnabled =的LocationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);            //获取网络状态
            isNetworkEnabled =的LocationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);            如果(isGPSEnabled&安培;!&安培;!isNetworkEnabled){
                //没有启用网络供应商
            }其他{
                this.canGetLocation = TRUE;
                //首先从网络提供商处获取位置
                如果(isNetworkEnabled){
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                    Log.d(网络,网络);
                    如果(的LocationManager!= NULL){
                        位置=的LocationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        如果(位置!= NULL){
                            纬度= location.getLatitude();
                            经度= location.getLongitude();
                        }
                    }
                }
                //如果GPS功能的获得纬度/长期使用GPS服务
                如果(isGPSEnabled){
                    如果(位置== NULL){
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES,这一点);
                        Log.d(GPS已启用,GPS功能的);
                        如果(的LocationManager!= NULL){
                            位置=的LocationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            如果(位置!= NULL){
                                纬度= location.getLatitude();
                                经度= location.getLongitude();
                            }
                        }
                    }
                }
            }        }赶上(例外五){
            e.printStackTrace();
        }        返回的位置;
    }    / **
     *停止使用GPS监听器
     *调用此函数将停止在你的应用程序中使用GPS
     * * /
    公共无效stopUsingGPS(){
        如果(的LocationManager!= NULL){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }    / **
     *函数来获取纬度
     * * /
    公共双getLatitude(){
        如果(位置!= NULL){
            纬度= location.getLatitude();
        }        //返回纬度
        返回纬度;
    }    / **
     *函数来获取经度
     * * /
    公共双getLongitude(){
        如果(位置!= NULL){
            经度= location.getLongitude();
        }        //返回经度
        返回经度;
    }    / **
     *功能检查启用GPS / WIFI
     * @返回布尔
     * * /
    公共布尔canGetLocation(){
        返回this.canGetLocation;
    }    / **
     *功能,以显示设置警告对话框
     *在pressing设置按钮将劳克设置选项
     * * /
    公共无效showSettingsAlert(){
        AlertDialog.Builder alertDialog =新AlertDialog.Builder(mContext);        //设置对话框标题
        alertDialog.setTitle(GPS是设置);        //设置对话框留言
        alertDialog.setMessage(GPS未启用你想要去设置菜单?);        //在pressing设置按钮
        alertDialog.setPositiveButton(设置,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){
                意向意图=新意图(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(意向);
            }
        });        //在pressing取消按钮
        alertDialog.setNegativeButton(取消,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释它){
            dialog.cancel();
            }
        });        //显示警报信息
        alertDialog.show();
    }    @覆盖
    公共无效onLocationChanged(地点){
    }    @覆盖
    公共无效onProviderDisabled(字符串提供商){
    }    @覆盖
    公共无效onProviderEnabled(字符串提供商){
    }    @覆盖
    公共无效onStatusChanged(字符串提供商,INT地位,捆绑演员){
    }    @覆盖
    公众的IBinder onBind(意向为arg0){
        返回null;
    }}


解决方案

您只能使用 MainActivity.this 如果BootComplete里面MainActivity一个嵌套类。

作为您GPSTracker只需要一个环境,你可以做

  GPS =新GPSTracker(背景);

I have this code, which i want to get GPS latitude and longitude from GPSTracker class But the error show

            gps=new GPSTracker(MainActivity.this);
            gps.getLatitude();

No enclosing instance of the type MainActivity is accessible in scope

The complete code BootComplete.java

public class BootComplete extends BroadcastReceiver{

//private static final String PREFS_NAME = null;
public static final String PREFS_NAME = "MyPrefs";
String storedSimSerial;
String currentSimSerial;
String email;       //email address input by user, generate email and sent to this address
String mobileno;    //mobile number input by user, generate SMS and send to this address
String sms;         //generate sms to user
public GPSTracker gps;


@Override
public void onReceive(final Context context, Intent intent) {

    SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
    storedSimSerial = prefs.getString("storedSimSerial", "");
    mobileno = prefs.getString("trustedNum", "");
    email = prefs.getString("Email", "");
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
    currentSimSerial = tm.getSimSerialNumber();

    if(currentSimSerial != null){
        if(currentSimSerial.compareToIgnoreCase(storedSimSerial) == 0){

        }else{

            prefs = context.getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor = prefs.edit();

            gps=new GPSTracker(MainActivity.this);
            gps.getLatitude();

            sms = "Alert!!!\nSim card changed.\nSim Serial Number:\n"+tm.getSimSerialNumber()+
                    "\nNetwork : "+ tm.getNetworkOperatorName()+"\nLatitude:\n" + gps.getLatitude();

            editor.putBoolean("SimChangeMail", true);
            editor.putString("subjectSimChange", "Your Sim card has changed.");
            editor.putString("bodySimChange","Sim Serial Number is :\n"+tm.getSimSerialNumber()+"\n" +
                    "This Sim serial number is unique and used to identify the owner.\nNetwork Operator is : "+
                    tm.getNetworkOperatorName()+
                    "\nThanks for using Mobile Security Application");
            editor.putString("SimChangeSms", sms);
            editor.commit();

            SmsManager sm = SmsManager.getDefault();
            String num = mobileno;
            sm.sendTextMessage(num, null, sms, null, null);
        }
    }else{

    }
}
}

GPSTracker.java

public class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @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;
    }

}

解决方案

you can only use MainActivity.this if BootComplete is a nested class inside MainActivity.

as your GPSTracker only needs a context, you can do

gps = new GPSTracker(context);

这篇关于类型MainActivity没有外围实例是在范围访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆