如何在Android中打开应用程序时获取本地通知?

时间:2014-06-03 08:50:16

标签: android uilocalnotification

我想在位置更改时设置本地通知。那么如何在后台激活我的应用并检查andorid.in位置列表中的更新位置我设置了我的整个逻辑以获取通知但我不知道为什么它不工作,而且应用程序没有在后台运行所以请帮助我。我是新手。

public class GPService extends Service {
NotificationManager nManager;
Notification notification ;
ArrayList<ImgProperties> arr ;
Calendar calender ;
String distance  ;
Location dest_location;
DBhelper dbHelper ;
Context context = this;
@Override
public IBinder onBind(Intent intent) {
return null;
}

private static void start() {
}
@SuppressWarnings("unused")
private static void stop() {
throw new UnsupportedOperationException("Not yet implemented");
    }


    private void show() {
        throw new UnsupportedOperationException("Not yet implemented");
    }


    private final IBinder mBinder = new LocalBinder();


    public class LocalBinder extends Binder {
        GPService getService() {
            return GPService.this;
        }
    }

    @Override
    public void onCreate() {
        SharedPreferences settings = getSharedPreferences("geodroid", 0);
        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER
                ,Integer.parseInt(settings.getString("GPS", "3"))*1000
               , Integer.parseInt(settings.getString("Dist", "1")), locationListenerGPS);


    }


    public  android.location.Location getCurrentGeoLocation()
    {
        android.location.Location location = null;
        LocationManager locManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        try {
            locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, locationListenerGPS);
            location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(location == null)
        {
            locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,0, locationListenerGPS);
            location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        return location;
    }





    private final LocationListener locationListenerGPS = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {


        }

        @Override
        public void onProviderEnabled(String provider) {


        }

        @Override
        public void onProviderDisabled(String provider) {


        }

        @SuppressWarnings("deprecation")
        @Override
        public void onLocationChanged(Location location) {

            calender = Calendar.getInstance();
            String Cdate = calender.get(Calendar.YEAR) + "/" + 
                        (calender.get(Calendar.MONTH) + 1) + "/" +
                            calender.get(Calendar.DAY_OF_MONTH);
            String Ctime = calender.get(Calendar.HOUR) + ":" +
                        calender.get(Calendar.MINUTE) ;

            Location loc = getCurrentGeoLocation();

            nManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
            dbHelper = new DBhelper(GPService.this);
            dbHelper.open();

            arr = dbHelper.getAllData();
            if(arr!= null){
            for(ImgProperties ipp : arr){
                String lt = ipp.getLat();
                String lon = ipp.getLng();

                dest_location = new Location("");

                    dest_location.setLatitude(Double.parseDouble(lt));
                    dest_location.setLongitude(Double.parseDouble(lon));

                    float[] results = new float[3];
                    android.location.Location.distanceBetween(loc.getLatitude(),
                            loc.getLongitude(), dest_location.getLatitude(), dest_location.getLongitude(), results);
                    double ddd = Utilities.metersToMile(results[0]);
                    int dd = (int) Math.ceil(ddd) ;
                    //double dis = loc.distanceTo(dest_location);
                    //distance = String.format("%.2f", dis);
                    //int dd = Integer.parseInt(distance);
                    Log.e("distacce", String.valueOf(dd));
                    Log.e("from date", String.valueOf(ipp.getFrom_date().equals(Cdate)));

                    Log.e("from date", String.valueOf(ipp.getFrom_time().equals(Ctime)));
                    Log.e("from date", String.valueOf(Integer.parseInt(ipp.getRadius())<=dd));

                    if(ipp.getIs_active().equals("Deactive")){

                        if(ipp.getFrom_date().equals(Cdate)){




                        if(ipp.getFrom_time().equals(Ctime)){

                            Log.e("", "1");
                                String act = "Active";
                                String patt = ipp.getBmp();
                                ImgProperties imgProp = new ImgProperties(act,patt);
                                dbHelper.updateSingle(imgProp);

                            notification =  new Notification(R.drawable.ic_launcher, "you click this", 11);

                            String title = context.getString(R.string.app_name);
                            Intent notificationIntent = new Intent(context, DashPage.class);
                            notificationIntent.putExtra("ms", "you click this");
                            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
                            notification.setLatestEventInfo(context, title, "you click this", intent);
                            notification.flags |= Notification.FLAG_AUTO_CANCEL;



                            notification.defaults |= Notification.DEFAULT_SOUND;

                         //   notification.defaults |= Notification.DEFAULT_VIBRATE;
                            nManager.notify(0, notification);
                           // stopSelf();
                        }

                        else if(Integer.parseInt(ipp.getRadius())<=dd){

                            Log.e("", "2");
                             String act = "Active";
                                String patt = ipp.getBmp();
                                ImgProperties imgProp = new ImgProperties(act,patt);
                                dbHelper.updateSingle(imgProp);
                            notification =  new Notification(R.drawable.ic_launcher, "you click this", 11);

                            String title = context.getString(R.string.app_name);
                            Intent notificationIntent = new Intent(context, DashPage.class);
                            notificationIntent.putExtra("ms", "you click this");
                            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
                            notification.setLatestEventInfo(context, title, "you click this", intent);
                            notification.flags |= Notification.FLAG_AUTO_CANCEL;


                            notification.defaults |= Notification.DEFAULT_SOUND;

                          //  notification.defaults |= Notification.DEFAULT_VIBRATE;
                            nManager.notify(1, notification);
                           // stopSelf();
                        }

                }
                else if(ipp.getFrom_time().equals(Ctime))
                {
                    Log.e("", "3");
                        String act = "Active";
                        String patt = ipp.getBmp();
                        ImgProperties imgProp = new ImgProperties(act,patt);
                        dbHelper.updateSingle(imgProp);

                    notification =  new Notification(R.drawable.ic_launcher, "you click this", 11);
                    //new Notification(icon, tickerText, when)

                    String title = context.getString(R.string.app_name);
                    Intent notificationIntent = new Intent(context, DashPage.class);
                    notificationIntent.putExtra("ms", "you click this");
                    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
                    notification.setLatestEventInfo(context, title, "you click this", intent);
                    notification.flags |= Notification.FLAG_AUTO_CANCEL;

                    notification.defaults |= Notification.DEFAULT_SOUND;

                  //  notification.defaults |= Notification.DEFAULT_VIBRATE;
                    nManager.notify(2, notification);
                  //  stopSelf();


                }
                else if(Integer.parseInt(ipp.getRadius())<=dd)
                {
                    Log.e("", "4");
                     String act = "Active";
                     String patt = ipp.getBmp();
                        ImgProperties imgProp = new ImgProperties(act,patt);
                        dbHelper.updateSingle(imgProp);



                        notification =  new Notification(R.drawable.ic_launcher, "you click this", 11);

                    String title = context.getString(R.string.app_name);
                    Intent notificationIntent = new Intent(context, DashPage.class);
                    notificationIntent.putExtra("ms", "you click this");
                    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
                    notification.setLatestEventInfo(context, title, "you click this", intent);
                    notification.flags |= Notification.FLAG_AUTO_CANCEL;

                    notification.defaults |= Notification.DEFAULT_SOUND;

                  //  notification.defaults |= Notification.DEFAULT_VIBRATE;
                    nManager.notify(3, notification);
                    stopSelf();

                }

                    }

            }
        }

        }
    };


                                 @Override
                                public int onStartCommand(Intent intent, int flags, int startId) {

                                     GPService.start();
                                    return START_STICKY;
                                }



                                 @Override
                                 public void onDestroy() {
                                     // Cancel the persistent notification.
                                     //mNM.cancel(NOTIFICATION);
                                        GPService.stop();
                                     // Tell the user we stopped.
                                     Toast.makeText(this, "geodroid service stopped", Toast.LENGTH_SHORT).show();
                                 }

1 个答案:

答案 0 :(得分:1)

别忘了添加一个Gps状态监听器,它将启动可用卫星的GPS坐标轮询。您应该在调用locationManager.requestLocationUpdates(...)之前执行此操作:

        locationManager.addGpsStatusListener(new GpsStatus.Listener() {
            @Override
            public void onGpsStatusChanged(int i) {
                log(getTimeStamp() + ":GSL:onGpsStatusChanged");
                switch (i) {
                    case GpsStatus.GPS_EVENT_STOPPED:
                        log(getTimeStamp() + ":GPS_EVENT_STOPPED");
                        break;
                    case GpsStatus.GPS_EVENT_STARTED:
                        log(getTimeStamp() + ":GPS_EVENT_STARTED");
                        break;
                    case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                        log(getTimeStamp() + ":GPS_EVENT_SATELLITE_STATUS");
                        GpsStatus gpsStatus = locationManager.getGpsStatus(null);
                        Iterable<GpsSatellite> gpsSatelliteIterable = gpsStatus.getSatellites();
                        Iterator<GpsSatellite> iterator = gpsSatelliteIterable.iterator();
                        int iCurrentSatIndex = 0;
                        while (iterator.hasNext()) {
                            GpsSatellite gpsSatellite = iterator.next();
                            log("SAT" + iCurrentSatIndex + ":Signal to Noise Ratio =" + gpsSatellite.getSnr());
                            log("SAT" + iCurrentSatIndex + ":Pseudo Random Number =" + gpsSatellite.getSnr());
                            log("SAT" + iCurrentSatIndex + ":Elevation =" + gpsSatellite.getElevation());
                            log("SAT" + iCurrentSatIndex + ":Azimuth =" + gpsSatellite.getAzimuth());
                            log("SAT" + iCurrentSatIndex + ":hasAlmanac =" + gpsSatellite.hasAlmanac());
                            log("SAT" + iCurrentSatIndex + ":hasEphemeris =" + gpsSatellite.hasEphemeris());
                            log("SAT" + iCurrentSatIndex + ":usedInFix =" + gpsSatellite.usedInFix());
                            iCurrentSatIndex++;
                        }
                        break;
                    case GpsStatus.GPS_EVENT_FIRST_FIX:
                        log(getTimeStamp() + ":GPS_EVENT_FIRST_FIX");
                        break;
                    default:
                        break;
                }
            }
        });