GeoFence警报未显示

时间:2016-05-10 13:24:56

标签: android google-maps android-maps-v2 geofencing android-geofence

使用下面的代码添加地理围栏后,Notify没有显示。即使onResult回调也是在取消成功。

GoogleApiClientApi onConnected()回调方法中添加地理围栏:

public void onConnected(Bundle bundle) {
        LocationServices.GeofencingApi.addGeofences(
                googleApiClient,
                getGeofencingRequest(),
                getGeofencePendingIntent()
        ).setResultCallback(this);
    }

请求地理围栏:

private GeofencingRequest getGeofencingRequest() {
        geoFenceList.add(new Geofence.Builder()
                .setRequestId("myFence")
                .setCircularRegion(68.441630, 77.310587, 2.0f)
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .build());
        GeofencingRequest.Builder builder = new GeofencingRequest.Builder();
        builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER);
        builder.addGeofences(geoFenceList);
        return builder.build();
    }

onResult()回调;

public void onResult(Status status) {
        if (status.isSuccess()){
            Toast.makeText(this,"Working",Toast.LENGTH_SHORT).show();//This Toast is showing/

        }else{
            Toast.makeText(this,"Not Working",Toast.LENGTH_SHORT).show();
        }
    }

触发通知的意图服务:

protected void onHandleIntent(Intent intent) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {

            return;
        }
        int geofenceTransition = geofencingEvent.getGeofenceTransition();
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {

            NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            Intent intent1 = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);

            Notification notification = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Your Geo")
                    .setContentText("This is My geo")
                    .setContentIntent(pendingNotificationIntent)
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setAutoCancel(true)
                    .build();
            notificationManager.notify(0, notification);
        } else {
        }    
    }

我认为IntentService没有动摇。我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

这是我的工作代码..我希望它的帮助你..

public class AreWeThereIntentService extends IntentService {
    private final String TAG = AreWeThereIntentService.class.getName();
    private SharedPreferences prefs;
    private Gson gson;
    MediaPlayer mp;

    public AreWeThereIntentService() {
        super("AreWeThereIntentService");
    }

    TinyDB tinyDB;
    ArrayList<Integer> myIntArr;

    @Override
    protected void onHandleIntent(Intent intent) {
        prefs = getApplicationContext().getSharedPreferences(
                Constants.SharedPrefs.Geofences, Context.MODE_PRIVATE);
        gson = new Gson();
        // 1. Get the event
        GeofencingEvent event = GeofencingEvent.fromIntent(intent);
        if (event != null) {
            if (event.hasError()) {
                onError(event.getErrorCode());
            } else {
                // 2. Get the transition type
                int transition = event.getGeofenceTransition();
                if (transition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                        transition == Geofence.GEOFENCE_TRANSITION_DWELL ||
                        transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
                    List<String> geofenceIds = new ArrayList<>();
                    // 3. Accumulate a list of event geofences
                    for (Geofence geofence : event.getTriggeringGeofences()) {
                        geofenceIds.add(geofence.getRequestId());
                    }
                    if (transition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                            transition == Geofence.GEOFENCE_TRANSITION_DWELL) {
                        // 4. Pass the geofence list to the notification method
                        onEnteredGeofences(geofenceIds);
                    }
                }
            }
        }
    }

    private void onEnteredGeofences(List<String> geofenceIds) {

        // 1. Outer loop over all geofenceIds
        for (String geofenceId : geofenceIds) {
            String geofenceName = "";
            // 2, Loop over all geofence keys in prefs and retrieve NamedGeofence from SharedPreferences
            Map<String, ?> keys = prefs.getAll();
            for (Map.Entry<String, ?> entry : keys.entrySet()) {
                String jsonString = prefs.getString(entry.getKey(), null);
                NamedGeofence namedGeofence = gson.fromJson(jsonString, NamedGeofence.class);
                if (namedGeofence.id.equals(geofenceId)) {
                    geofenceName = namedGeofence.name;
                    break;
                }
            }
            myIntArr.add(Calendar.DAY_OF_WEEK);
            int day = Calendar.DAY_OF_WEEK;
            myIntArr = tinyDB.getListInt("myList");

            // 3. Set the notification text and send the notification
            String contextText =
                    String.format(this.getResources().getString(R.string.Notification_Text), geofenceName);
            // 1. Create a NotificationManager
            NotificationManager notificationManager =
                    (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

            Intent intent = new Intent(this, MapsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                    + "://" + getPackageName() + "/raw/battlefield");

            int timeout = 20000;
            long[] pattern = {0, 100, 200, 300};
            mp = new MediaPlayer();
            mp = MediaPlayer.create(getBaseContext(), R.raw.battlefield);
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setLooping(true);
            mp.start();

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mp.isPlaying()) {
                        mp.stop();
                    }
                }
            }, timeout);

            Notification notification = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.map_marker_icon)
                    .setContentTitle(this.getResources().getString(R.string.Notification_Title))
                    .setContentText(contextText)
                    .setContentIntent(pendingNotificationIntent)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(contextText))
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setAutoCancel(true)
                    .setWhen(System.currentTimeMillis())
                    .build();
            notificationManager.notify(0, notification);

                 /* AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            Intent myIntent = new Intent(this, AlarmReciver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, 1, pendingIntent);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 *30), pendingIntent);*/


        }
    }

    private void onError(int i) {
        Log.e(TAG, "Geofencing Error: " + i);
    }
}

并确保在清单文件中添加此行:

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

这是我在项目geofence alert

中实施的链接