簡體   English   中英

java.lang.ClassCastException:com.example.login.app.AppController無法轉換為android.app.Activity

[英]java.lang.ClassCastException: com.example.login.app.AppController cannot be cast to android.app.Activity

我正在嘗試獲取移動設備的IMEI。 if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getApplicationContext(), Manifest.permission.READ_PHONE_STATE))方法重寫被獲取錯誤。 並且還想知道我們是否可以在服務類中訪問IMEI no。感謝這是我的服務類代碼。

public class LocationService extends Service implements LocationListener {

private static String url_insert_location = "http://localhost/testing/insert.php";
public static String LOG = "Log";

JSONParser jsonParser = new JSONParser();

private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;

boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 0 meters

private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
private static final long MIN_TIME_BW_UPDATES = 1000; // 1 second
protected LocationManager locationManager;

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

public LocationService() {
    super();
    mContext = LocationService.this;
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    String currentDateandTime = sdf.format(new Date());
    Toast.makeText(this,( "latitude" + latitude +"longitude" + longitude + currentDateandTime), Toast.LENGTH_LONG).show();

    Log.i(LOG, "Service started");
    Log.i("asd", "This is sparta");
    Log.i("a",currentDateandTime);
    loadIMEI();
new SendToServer().execute(Double.toString(getLocation().getLongitude()), Double.toString(getLocation().getLatitude()));

    return START_STICKY;
}

@Override
public void onCreate() {
    super.onCreate();
    Log.i(LOG, "Service created");
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.i(LOG, "Service destroyed");
}

class SendToServer extends AsyncTask<String, String, String> {


    @Override
    protected String doInBackground(String... la) {

        try {

            Log.i("string", la[0]);
            String longi = la[0];
            String lati = la[1];

            // Building Parameters
            Log.d("value", lati);
            Log.d("value", longi);
            ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("longitude", longi));
            params.add(new BasicNameValuePair("latitude", lati));
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url_insert_location);
            HttpResponse httpresponse = httpclient.execute(httppost);


        } catch (Exception e) {
            Log.i("error", e.toString());
        }

        return "call";
    }
}
public void loadIMEI() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
            != PackageManager.PERMISSION_GRANTED) {
        requestReadPhoneStatePermission();
    } else {

        doPermissionGrantedStuffs();
    }
}

private void requestReadPhoneStatePermission() {
    if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getApplicationContext(),
            Manifest.permission.READ_PHONE_STATE)) {
        new AlertDialog.Builder(this)
                .setTitle("Permission Request")
                .setMessage("permission_read_phone_state_rationale")
                .setCancelable(false)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //re-request
                        ActivityCompat.requestPermissions((Activity) getApplicationContext(),
                                new String[]{Manifest.permission.READ_PHONE_STATE},
                                MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
                    }
                })
                .setIcon(R.drawable.ic_cast_on_light)
                .show();
    } else {

        ActivityCompat.requestPermissions((Activity) getApplicationContext(), new String[]{Manifest.permission.READ_PHONE_STATE},
                MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
    }
}

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {

    if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
        // Received permission result for READ_PHONE_STATE permission.est.");
        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // READ_PHONE_STATE permission has been granted, proceed with displaying IMEI Number
            //alertAlert(getString(R.string.permision_available_read_phone_state));
            doPermissionGrantedStuffs();
        } else {
            alertAlert("permission not granted");
        }
    }
}

private void alertAlert(String msg) {
    new AlertDialog.Builder(this)
            .setTitle("Permission Request")
            .setMessage(msg)
            .setCancelable(false)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // do somthing here
                }
            })
            .setIcon(R.drawable.ic_plusone_medium_off_client)
            .show();
}
public void doPermissionGrantedStuffs() {
    //Have an  object of TelephonyManager
    TelephonyManager tm =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    //Get IMEI Number of Phone  //////////////// for this example i only need the IMEI
    String IMEINumber=tm.getDeviceId();

}
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) {
                //updates will be send according to these arguments
                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) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return 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;
}

    @Override
    public void onLocationChanged(Location location) {
      SendToServer().execute(Double.toString(getLocation().getLongitude()),Double.toString(getLocation().getLatitude()));
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras){
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onProviderDisabled(String provider) {
    }

您不能將ApplicationContext強制轉換為Activity,因為它不是Activity。 我想用一個Activity實例構造服務會導致內存泄漏,因此我建議您在其他地方(例如在啟動Service的活動中)請求許可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM