0

我希望我的应用程序在用户进入地理围栏区域时发出通知。它既不会发出通知,也不会在我为获取地理围栏彩色视图而定义的地图上显示 Circle。怎么了 ?请与我合作,这件事花了我很长时间。我会感谢你的合作。

主文件,

 public class MainActivity extends FragmentActivity{

protected GoogleMap gMap;
private LocationManager locationManager;

    double clat,clong;
    List<Geofence> mGeofenceList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    if (gMap == null) {
            Toast.makeText(this, "Google Maps not available",           
         Toast.LENGTH_LONG).show();}

      locate();
      geofencing();

    gMap.setMyLocationEnabled(true);         

        Intent intent = new Intent(this,TransitionsIntentService.class);
        startService(intent);
}   


     private void geofencing() {

     // Instantiate the current List of geofences
           mGeofenceList = new ArrayList<Geofence>();
           Geofence geofence1 = new Geofence.Builder()
    .setRequestId("your target place")
    .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
    .setCircularRegion(clat,clong, 2000.0f)
    .setExpirationDuration(Geofence.NEVER_EXPIRE)
    .build();

           mGeofenceList.add(geofence1);
           CircleOptions circleOptions = new CircleOptions()
     .center( new LatLng(clat,clong) )
     .radius(20000)
     .fillColor(Color.BLUE)
     .strokeColor(Color.BLUE);

           // Get back the mutable Circle
            gMap.addCircle(circleOptions);

    }

        private void locate() {


    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {

            clat=location.getLatitude();
            clong=location.getLongitude();

        }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}
      };

        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 10, locationListener);              

    }

  }

TransitionsIntentService.java 文件,

 public class TransitionsIntentService extends IntentService {
     public static final String TRANSITION_INTENT_SERVICE = "ReceiveTransitionsIntentService";
   private List<Geofence> mGeofenceList;
    public TransitionsIntentService() {
       super(TRANSITION_INTENT_SERVICE);
   }
    @Override
      protected void onHandleIntent(Intent intent) {
          // First check for errors
        if (LocationClient.hasError(intent)) {
         // Get the error code with a static method
        int errorCode = LocationClient.getErrorCode(intent);
        // Log the error
        Log.e("ReceiveTransitionsIntentService",
                "Location Services error: " +
                Integer.toString(errorCode));
        /*
         * You can also send the error code to an Activity or
         * Fragment with a broadcast Intent
         */
       /*
        * If there's no error, get the transition type and the IDs
        * of the geofence or geofences that triggered the transition
        */
       } else {
        // Get the type of transition (entry or exit)
        int transitionType =
                LocationClient.getGeofenceTransition(intent);
        // Test that a valid transition was reported
        if (
            (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER)
             ||
            (transitionType == Geofence.GEOFENCE_TRANSITION_EXIT)
           ) {
            List <Geofence> triggerList =
                    getTriggeringGeofences(intent);


            String[] triggerIds = new String[mGeofenceList.size()];

            for (int i = 0; i < triggerIds.length; i++) {
                // Store the Id of each geofence
                triggerIds[i] = triggerList.get(i).getRequestId();
            }
            /*
             * At this point, you can store the IDs for further use
             * display them, or display the details associated with
             * them.
             */
        }
       // An invalid transition was reported
        else {
          Log.e("ReceiveTransitionsIntentService",
                "Geofence transition error: ");

          }
       }
    }



  private List<Geofence> getTriggeringGeofences(Intent intent) {
    // TODO Auto-generated method stub
     notification();
    return null;
  }



         @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
         private void notification()
    {
    NotificationCompat.Builder mBuilder =
        new NotificationCompat.Builder(this)
        .setSmallIcon(R.drawable.jollyr)
        .setPriority(NotificationCompat.PRIORITY_MAX)
        .setContentTitle("Flood Warning")
        .setContentText("You are in Danger Zone");


    Intent i= new Intent(this,MainActivity.class);

    /* The stack builder object will contain an artificial back stack for the
    started Activity.
    This ensures that navigating backward from the Activity leads out of
    your application to the Home screen.*/
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    // Adds the back stack for the Intent (but not the Intent itself)
   stackBuilder.addParentStack(MainActivity.class);
   // Adds the Intent that starts the Activity to the top of the stack
   stackBuilder.addNextIntent(i);
   PendingIntent pi =
        stackBuilder.getPendingIntent(
            0,
            PendingIntent.FLAG_UPDATE_CURRENT
        );
   mBuilder.setContentIntent(pi);
   // Sets an ID for the notification
        int nId = 001;
   // Gets an instance of the NotificationManager service
        NotificationManager mNotifyMgr = 
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // Builds the notification and issues it.   
        mNotifyMgr.notify(nId, mBuilder.build());


       }
   }    

清单文件,

    <application
       android:allowBackup="true"
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >

    <activity
        android:name="com.example.map.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>

        <service android:name=".TransitionsIntentService" />

         <meta-data
          android:name="com.google.android.maps.v2.API_KEY"
          android:value="AIzaSyBeJoGKnhxYps-youI1xfMZn6S2G05l0PM" />

   </application>
4

2 回答 2

1

你的清单不见了

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
于 2014-06-12T05:19:41.063 回答
0

我相信你的清单不见了

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

或者

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

Fine 是您想要的,基于网络的位置可能不够准确。

于 2013-11-12T10:19:38.120 回答