2015-10-15 26 views
0

我正在尝试android配置单元的教程,以了解如何跟踪用户的位置,并显示他们附近的地方。我想通知用户有关位置更改并将其重定向到应用程序的第一个屏幕。我曾尝试调用包含从onlocationchanged方法通知代码类,但它显示了在pendingintent.getactivity空指针异常()我已经加入清单文件的所有权限下面的代码:通知用户有关位置更新自动android

GPSTracker.java:

这是包含onlocationchanged从我试图调用shownotif()的文件。 公共类GPSTracker延伸服务实现LocationListener的{

private final Context mContext; 
Notif n = new Notif(); 
// flag for GPS status 
boolean isGPSEnabled = false; 

// flag for network status 
boolean isNetworkEnabled = false; 

// flag for GPS status 
boolean canGetLocation = false; 

Location location = null; // location 
double latitude; // latitude 
double longitude; // longitude 

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

// The minimum time between updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 0; 

// 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 Enabled"); 
       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", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 
     Toast.makeText(getApplicationContext(), "Location changed",Toast.LENGTH_SHORT).show(); 

    } 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) { 
     //notification 
    if(location!=null) { 
     n.shownotif(this); 
    } 

} 

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

}

这是notif.java

public class Notif { 
void shownotif(Context context) 
{ 

    PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0); 
    Notification noti = new NotificationCompat.Builder(context) 
      .setContentTitle("Notification") 
      .setContentText("There are new places to visit") 
      .setSmallIcon(android.R.drawable.stat_sys_warning) 
      .setContentIntent(pi) 
      .setDefaults(Notification.DEFAULT_SOUND) 
      .setDefaults(Notification.DEFAULT_VIBRATE) 
      .setWhen(System.currentTimeMillis()) 
      .setAutoCancel(true) 
      .build(); 
    NotificationManager mgr = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); 
    mgr.notify(0,noti); 
} 

}

,这是mainactivity.java onCreate方法

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    cd = new ConnectionDetector(getApplicationContext()); 

    // Check if Internet present 
    isInternetPresent = cd.isConnectingToInternet(); 
    if (!isInternetPresent) { 
     // Internet Connection is not present 
     alert.showAlertDialog(MainActivity.this, "Internet Connection Error", 
       "Please connect to working Internet connection", false); 
     // stop executing code by return 
     return; 
    } 

    // creating GPS Class object 
    gps = new GPSTracker(this); 

    // check if GPS location can get 
    if (gps.canGetLocation()) { 
     Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude()); 
    } else { 
     // Can't get user's current location 
     alert.showAlertDialog(MainActivity.this, "GPS Status", 
       "Couldn't get location information. Please enable GPS", 
       false); 
     // stop executing code by return 
     return; 
    } 

    // Getting listview 
    lv = (ListView) findViewById(R.id.list); 

    // button show on map 
    btnShowOnMap = (Button) findViewById(R.id.btn_show_map); 

    // calling background Async task to load Google Places 
    // After getting places from Google all the data is shown in listview 
    new LoadPlaces().execute(); 

    /** Button click event for shown on map */ 
    btnShowOnMap.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      Intent i = new Intent(getApplicationContext(), 
        PlacesMapActivity.class); 
      // Sending user current geo location 
      i.putExtra("user_latitude", Double.toString(gps.getLatitude())); 
      i.putExtra("user_longitude", Double.toString(gps.getLongitude())); 

      // passing near places to map activity 
      i.putExtra("near_places", nearPlaces); 
      // staring activity 
      startActivity(i); 
     } 
    }); 


    /** 
    * ListItem click event 
    * On selecting a listitem SinglePlaceActivity is launched 
    * */ 
    lv.setOnItemClickListener(new OnItemClickListener() { 

     @Override 
     public void onItemClick(AdapterView<?> parent, View view, 
           int position, long id) { 
      // getting values from selected ListItem 
      String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString(); 

      // Starting new intent 
      Intent in = new Intent(getApplicationContext(), 
        SinglePlaceActivity.class); 

      // Sending place refrence id to single place activity 
      // place refrence id used to get "Place full details" 
      in.putExtra(KEY_REFERENCE, reference); 
      startActivity(in); 
     } 
    }); 
} 

回答

0

我已经打过电话,它包含onlocationchanged方法通知代码类,但它显示了在pendingintent.getactivity空指针异常()。

PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0); 

正如我得到你所得到的方面空,所以通过mContext内onLocationChanged .e.g

@Override 
public void onLocationChanged(Location location) { 
     //notification 
    if(location!=null) { 
     n.shownotif(mContext); 
    } 
+0

谢谢soooooooooooo多!!!!!!它的工作正常!!!!! – kjs

+0

尽管我已经更改了min_distance和time的值,但它仍然每秒都会发出通知。我没有得到什么错误? – kjs

0

您正在传递错误的上下文。你可能想这样做,而不是:

@Override 
public void onLocationChanged(Location location) { 
    //notification 
    if(location!=null) { 
     n.shownotif(mContext); 
    } 

} 
+0

谢谢SOOOOO多尼克回答!它的工作正常! – kjs