2016-08-19 248 views
0

我正在嘗試獲取移動設備的IMEI號,並在if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) getApplicationContext(), Manifest.permission.READ_PHONE_STATE))方法覆蓋上出錯。並且還想知道我們是否可以訪問服務類中的IMEI號。感謝 這是我的服務類代碼。java.lang.ClassCastException:com.example.login.app.AppController無法轉換爲android.app.Activity

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) { 
    } 

回答

1

您不能將ApplicationContext轉換爲Activity,因爲它不是一個Activity。我猜想用Activity實例構造服務會導致內存泄漏,所以我建議你在其他位置請求權限,例如在啓動服務的活動中。

+0

謝謝,我明白了 –

+0

不客氣! –

+0

當我發送currentTimeDate到服務器通過Double.toString(Double.parseDouble(currentDateandTime)發生錯誤無效雙任何解決方案爲此 –

相關問題