1

我的代码在 Android 版本是 2.3 中运行。我应该在代码中编辑什么以便它在 4.2 及更高版本中也能工作?

我的代码,

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

    }

清单.xml

<?xml version="1.0" encoding="utf-8"?>
        <manifest xmlns:android="http://schemas.android.com/apk/res/android"
            package="com.example.safetymobile"
            android:versionCode="2"
            android:versionName="1.2" >

            <uses-permission android:name="android.permission.READ_CONTACTS" />
            <uses-permission android:name="android.permission.READ_PHONE_STATE" />
            <uses-permission android:name="android.permission.INTERNET" />
            <uses-permission android:name="android.permission.CALL_PHONE" >
            </uses-permission>
            <uses-permission android:name="android.permission.CAMERA" />

            <uses-feature android:name="android.hardware.camera" />

            <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
            </uses-permission>
            <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
            </uses-permission>
            <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
            <uses-permission android:name="android.permission.BLUETOOTH" />
            <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
            <uses-permission android:name="android.permission.VIBRATE" >
            </uses-permission>
            <uses-permission android:name="android.permission.WAKE_LOCK" >
            </uses-permission>
            <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

            <uses-sdk
                android:minSdkVersion="8"
                android:targetSdkVersion="17" />

            <uses-permission android:name="android.permission.SEND_SMS" />

            <application
                android:allowBackup="true"
                android:icon="@drawable/ic_launcher"
                android:label="@string/app_name"
                android:theme="@style/AppTheme" >
                <activity
                    android:name="com.example.safetymobile.MainActivity"
                    android:label="@string/app_name" 
                    android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen"
                    android:clearTaskOnLaunch="true"
                    >
                    <intent-filter>
                        <action android:name="android.intent.action.MAIN" />

                        <category android:name="android.intent.category.LAUNCHER" />
                    </intent-filter>
                </activity>
                <activity
                    android:name="com.example.safetymobile.ContactList"
                    android:label="@string/title_activity_contact_list" >
                </activity>
                <activity
                    android:name="com.example.safetymobile.Change_setting"
                    android:label="@string/title_activity_change_setting"
                    android:clearTaskOnLaunch="true" >
                </activity>
                <activity
                    android:name="com.example.safetymobile.CallContent"
                    android:label="@string/title_activity_call_content"
                    android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
                </activity>
                <activity
                    android:name="com.example.safetymobile.SMS"
                    android:label="@string/title_activity_sms"
                    android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
                </activity>
                <activity
                    android:name="com.example.safetymobile.Alication_list"
                    android:label="@string/title_activity_alication_list"  >
                </activity>
                <activity
                    android:name="com.example.safetymobile.Apps"
                    android:label="@string/title_activity_apps" 
                    android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen">
                </activity>
                <activity
                    android:name="com.example.safetymobile.Pass"
                    android:label="@string/title_activity_pass" >
                </activity>
                <activity
                    android:name="com.example.safetymobile.ChangePass"
                    android:label="@string/title_activity_change_pass" >
                </activity>
                <activity
                    android:name="com.example.safetymobile.GPS"
                    android:label="@string/title_activity_gps" >
                </activity>
                <activity
                    android:name="com.example.safetymobile.LightActivity"
                    android:label="@string/title_activity_light"
                    android:theme="@android:style/Theme.Light.NoTitleBar.Fullscreen" >
                </activity>
                <receiver android:name=".StartupActivity">
                    <intent-filter>
                        <action android:name="android.intent.action.BOOT_COMPLETED"></action>
                        <category android:name="android.intent.category.DEFAULT"></category>
                    </intent-filter>
                </receiver>
            </application>

        </manifest>

日志猫:

10-30 09:37:31.816: E/AndroidRuntime(1260): FATAL EXCEPTION: main
10-30 09:37:31.816: E/AndroidRuntime(1260): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.safetymobile/com.example.safetymobile.MainActivity}: java.lang.NullPointerException
10-30 09:37:31.816: E/AndroidRuntime(1260):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at android.app.ActivityThread.main(ActivityThread.java:5041)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at java.lang.reflect.Method.invokeNative(Native Method)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at java.lang.reflect.Method.invoke(Method.java:511)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at dalvik.system.NativeStart.main(Native Method)
10-30 09:37:31.816: E/AndroidRuntime(1260): Caused by: java.lang.NullPointerException
10-30 09:37:31.816: E/AndroidRuntime(1260):  at com.example.safetymobile.MainActivity.onCreate(MainActivity.java:123)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at android.app.Activity.performCreate(Activity.java:5104)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-30 09:37:31.816: E/AndroidRuntime(1260):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)

如何将 android 应用程序版本 2.3 更改为 4.2?

我正在使用日食 ADT

onCreate 部分 MainActivity

gps = new GPSTracker(MainActivity.this);
  // check if GPS enabled  
    if(gps.canGetLocation())
     {
     latitude = gps.getLatitude();
     longitude = gps.getLongitude();
     }
    else{
        // can't get location
        // GPS or Network is not enabled
        // Ask user to enable GPS/network in settings
        gps.showSettingsAlert();
     }
  ImageButton btn=(ImageButton)findViewById(R.id.application);
  btn.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    Intent t = new Intent(v.getContext(),Apps.class);
    startActivity(call);
   }

  });
  mp2 = MediaPlayer.create(this,R.drawable.emsound);
  button = (Button) findViewById(R.id.buttonFlashlight);
  button1 = (Button) findViewById(R.id.panic);
  final Context context = this;
  @SuppressWarnings("unused")
  final SensorManager mSensorManager;
  final PowerManager mPowerManager;
  final WindowManager mWindowManager;
  final WakeLock mWakeLock;
    // Get an instance of the SensorManager
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        // Get an instance of the PowerManager
        mPowerManager = (PowerManager) getSystemService(POWER_SERVICE);

        // Get an instance of the WindowManager
        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        mWindowManager.getDefaultDisplay();

        // Create a bright wake lock
        mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, getClass()
                .getName());
  PackageManager pm = context.getPackageManager();

  /*-----------check if camera is available----------*/

  if(!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA))
  {
   @SuppressWarnings("unused")
   Logger message;
   Log.e("err", "Device has no camera!");
   Toast.makeText(getApplicationContext(),
   "Your device doesn't have camera!",Toast.LENGTH_SHORT).show();
   return;
  }

     camera = Camera.open();
     p = camera.getParameters();
  button.setOnClickListener(new OnClickListener() 
  {

   public void onClick(View v) 
      {
    if (isFlashOn) {
     Toast.makeText(getApplicationContext(), "torch is turned off!", Toast.LENGTH_SHORT).show();
     Log.i("info", "torch is turned off!"); 

     /*----------- if camera flash is available----------*/
     if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
     {
     p.setFlashMode(Parameters.FLASH_MODE_OFF);
     camera.setParameters(p);    

     //button.setsetText("Torch-ON");
     }

     /*----------- if camera flash is not available----------*/
     else
     {
      //Toast.makeText(getApplicationContext(), "flash is turned off!", Toast.LENGTH_SHORT).show();
        WindowManager.LayoutParams params = getWindow().getAttributes();
                    params.screenBrightness = -1;
                    getWindow().setAttributes(params);
      mWakeLock.release();
     }

     isFlashOn = false;
    } 
    else 
    {
     Toast.makeText(getApplicationContext(), "torch is turned on!", Toast.LENGTH_SHORT).show();
     Log.i("info", "torch is turned on!");

     /*----------- if camera flash is available----------*/
     if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH))
     {
     p.setFlashMode(Parameters.FLASH_MODE_TORCH);
     camera.setParameters(p);
     }

     /*----------- if camera flash is not available----------*/
     else
     {
      //Toast.makeText(getApplicationContext(), "flash is turned off!", Toast.LENGTH_SHORT).show();
     /* mWakeLock.acquire();
      WindowManager.LayoutParams params = getWindow().getAttributes();
                   params.screenBrightness = 1.0f;
                   getWindow().setAttributes(params);*/

                  DoToLight();
     }

     isFlashOn = true;
     //button.setText("Torch-OFF");
    }
      }
   });
4

2 回答 2

2

首先右键单击项目 -> 属性 -> Android -> 选择 4.2 版本(android 或 google api) -> 应用 -> ok

快乐的编码...

于 2013-10-30T07:50:25.093 回答
0

更改应用程序版本:

right click on project -> Property -> Android -> select 4.2 version (as per your requirement) -> Apply -> ok.

right click on project ->Run As->Run Confi.->in android Application tab(left pannel),right pannel with android tab select your project->target Tab(check Launch on all compatible and select active device)

如果有任何问题发表评论。

于 2013-10-30T09:29:51.193 回答