我是否正确使用闹钟?

发布于 2024-12-02 20:49:32 字数 7780 浏览 0 评论 0原文

我有一个 Android 应用程序,它将每 x 分钟记录一次数据。闹钟响起的时间基于设置页面(10 或 30 分钟)。当警报进入启动画面时,它首先被激活。我的问题是,当我在手机上使用它时,它似乎没有被调用,所以我希望有人能告诉我我是否正确使用了该功能。

    if (prefs.getBoolean("backgroundupdates", true)) {
        Intent setAlarm = new Intent(Splash.this,
                UpdateLocation.class);
        PendingIntent pendingIntent = PendingIntent.getService(
                Splash.this, 0, setAlarm, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(
                "yyyy-MM-dd hh:mm:ssaa");
        History.addHistory(sdf.format(calendar.getTime()), "App Started", "");
        calendar.setTimeInMillis(System.currentTimeMillis());

        int UPDATE_TIME = prefs.getInt("Update_time", 30);
        calendar.add(Calendar.MINUTE, UPDATE_TIME);
        alarmManager.set(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), pendingIntent);


    }

这会检查后台更新是否开启,并

在我的 UpdateLocation.class 中设置一个 UPDATE_TIME 分钟(默认 30)的警报。我在底部有这个

    Intent setAlarm = new Intent(UpdateLocation.this,
                    UpdateLocation.class);
            PendingIntent pendingIntent = PendingIntent.getService(
                    UpdateLocation.this, 0, setAlarm, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            int UPDATE_TIME = prefs.getInt("Update_time", 30);
            calendar.add(Calendar.MINUTE, UPDATE_TIME);
            alarmManager.set(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(), pendingIntent);

,这样警报将在 UPDATE_TIME 分钟内再次调用自己。我这样做的原因是因为 UPDATE_TIME 可能会改变(取决于用户偏好)

谢谢!

这里编辑是我的 UpdateLocation.class

public class UpdateLocation extends IntentService {
    public static final String id = "";

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

    @Override
    protected void onHandleIntent(Intent intent) {

        SharedPreferences prefs = getSharedPreferences("Settings", 0);
        final String id = prefs.getString("ID", "");
        if (prefs.getBoolean("backgroundupdates", true)) {
            HttpParams httpParams = new BasicHttpParams();
            // 30seconds and it stops
            HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
            HttpConnectionParams.setSoTimeout(httpParams, 30000);
            DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
            HttpPost httpost = new HttpPost(
                    "http://iphone-radar.com/gps/gps_locations");

            JSONObject holder = new JSONObject();

            try {
                holder.put("id", id);
                LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                String bestProvider = locationManager.getBestProvider(criteria,
                        false);
                LocationListener loc_listener = new LocationListener() {

                    @Override
                    public void onStatusChanged(String provider, int status,
                            Bundle extras) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onLocationChanged(Location location) {
                        // TODO Auto-generated method stub

                    }
                };
                try {
                    Looper.prepare();
                    locationManager.requestLocationUpdates(bestProvider, 0, 0,
                            loc_listener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Location location = locationManager
                        .getLastKnownLocation(bestProvider);
                Calendar c = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "hh:mmaa MM/dd/yyyy");
                holder.put("time", sdf.format(c.getTime()));
                holder.put("time_since_epoch", System.currentTimeMillis()/1000);
                try {
                    holder.put("lat", location.getLatitude());
                    holder.put("lon", location.getLongitude());
                } catch (NullPointerException e) {
                    try {
                        holder.put("lat", -1.0);
                        holder.put("lon", -1.0);
                    } catch (JSONException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }

                StringEntity se = new StringEntity(holder.toString());
                httpost.setEntity(se);
                httpost.setHeader("Accept", "application/json");
                httpost.setHeader("Content-type", "application/json");

                ResponseHandler responseHandler = new BasicResponseHandler();
                String response = httpclient.execute(httpost, responseHandler);
                org.json.JSONObject obj;
                SimpleDateFormat sdf2 = new SimpleDateFormat(
                        "yyyy-MM-dd hh:mm:ssaa");
                try{
                History.addHistory(sdf2.format(c.getTime()), "GPS",
                        "Latitude: " + location.getLatitude() + "\n"
                                + "Longitude: " + location.getLongitude());}
                catch(NullPointerException e){
                    History.addHistory(sdf2.format(c.getTime()), "GPS",
                            "Latitude: " + "No Signal" + "\n"
                                    + "Longitude: " + "No Signal");
                }
                obj = new org.json.JSONObject(response);
                Intent setAlarm = new Intent(UpdateLocation.this,
                        UpdateLocation.class);
                PendingIntent pendingIntent = PendingIntent.getService(
                        UpdateLocation.this, 0, setAlarm, 0);
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(System.currentTimeMillis());
                int UPDATE_TIME = prefs.getInt("Update_time", 30);
                calendar.add(Calendar.MINUTE, UPDATE_TIME);
                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), pendingIntent);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

}

注意,我没有广播接收器,我不太确定如何使用它,所以任何示例都会非常有帮助。

I have an android app that will record data every x mins. The time the alarm goes off is based on the settings page (either 10 or 30 mins). The alarm is first activated when it goes into the splash screen. My problem is, it doesnt seem to be called when I'm using it on my phone and so I was hoping someone could tell me if I'm using the function properly.

    if (prefs.getBoolean("backgroundupdates", true)) {
        Intent setAlarm = new Intent(Splash.this,
                UpdateLocation.class);
        PendingIntent pendingIntent = PendingIntent.getService(
                Splash.this, 0, setAlarm, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(
                "yyyy-MM-dd hh:mm:ssaa");
        History.addHistory(sdf.format(calendar.getTime()), "App Started", "");
        calendar.setTimeInMillis(System.currentTimeMillis());

        int UPDATE_TIME = prefs.getInt("Update_time", 30);
        calendar.add(Calendar.MINUTE, UPDATE_TIME);
        alarmManager.set(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(), pendingIntent);


    }

This checks if background updates are on and sets an alarm for UPDATE_TIME mins (default 30)

in my UpdateLocation.class I have this in the bottom

    Intent setAlarm = new Intent(UpdateLocation.this,
                    UpdateLocation.class);
            PendingIntent pendingIntent = PendingIntent.getService(
                    UpdateLocation.this, 0, setAlarm, 0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            int UPDATE_TIME = prefs.getInt("Update_time", 30);
            calendar.add(Calendar.MINUTE, UPDATE_TIME);
            alarmManager.set(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(), pendingIntent);

This is so that the alarm will call itself again in UPDATE_TIME mins. The reason I'm doing it this way is because UPDATE_TIME may change (depending on user preferences)

Thanks!

EDIT here is my UpdateLocation.class

public class UpdateLocation extends IntentService {
    public static final String id = "";

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

    @Override
    protected void onHandleIntent(Intent intent) {

        SharedPreferences prefs = getSharedPreferences("Settings", 0);
        final String id = prefs.getString("ID", "");
        if (prefs.getBoolean("backgroundupdates", true)) {
            HttpParams httpParams = new BasicHttpParams();
            // 30seconds and it stops
            HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
            HttpConnectionParams.setSoTimeout(httpParams, 30000);
            DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);
            HttpPost httpost = new HttpPost(
                    "http://iphone-radar.com/gps/gps_locations");

            JSONObject holder = new JSONObject();

            try {
                holder.put("id", id);
                LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                String bestProvider = locationManager.getBestProvider(criteria,
                        false);
                LocationListener loc_listener = new LocationListener() {

                    @Override
                    public void onStatusChanged(String provider, int status,
                            Bundle extras) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onProviderEnabled(String provider) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onLocationChanged(Location location) {
                        // TODO Auto-generated method stub

                    }
                };
                try {
                    Looper.prepare();
                    locationManager.requestLocationUpdates(bestProvider, 0, 0,
                            loc_listener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Location location = locationManager
                        .getLastKnownLocation(bestProvider);
                Calendar c = Calendar.getInstance();
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "hh:mmaa MM/dd/yyyy");
                holder.put("time", sdf.format(c.getTime()));
                holder.put("time_since_epoch", System.currentTimeMillis()/1000);
                try {
                    holder.put("lat", location.getLatitude());
                    holder.put("lon", location.getLongitude());
                } catch (NullPointerException e) {
                    try {
                        holder.put("lat", -1.0);
                        holder.put("lon", -1.0);
                    } catch (JSONException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }

                StringEntity se = new StringEntity(holder.toString());
                httpost.setEntity(se);
                httpost.setHeader("Accept", "application/json");
                httpost.setHeader("Content-type", "application/json");

                ResponseHandler responseHandler = new BasicResponseHandler();
                String response = httpclient.execute(httpost, responseHandler);
                org.json.JSONObject obj;
                SimpleDateFormat sdf2 = new SimpleDateFormat(
                        "yyyy-MM-dd hh:mm:ssaa");
                try{
                History.addHistory(sdf2.format(c.getTime()), "GPS",
                        "Latitude: " + location.getLatitude() + "\n"
                                + "Longitude: " + location.getLongitude());}
                catch(NullPointerException e){
                    History.addHistory(sdf2.format(c.getTime()), "GPS",
                            "Latitude: " + "No Signal" + "\n"
                                    + "Longitude: " + "No Signal");
                }
                obj = new org.json.JSONObject(response);
                Intent setAlarm = new Intent(UpdateLocation.this,
                        UpdateLocation.class);
                PendingIntent pendingIntent = PendingIntent.getService(
                        UpdateLocation.this, 0, setAlarm, 0);
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(System.currentTimeMillis());
                int UPDATE_TIME = prefs.getInt("Update_time", 30);
                calendar.add(Calendar.MINUTE, UPDATE_TIME);
                alarmManager.set(AlarmManager.RTC_WAKEUP,
                        calendar.getTimeInMillis(), pendingIntent);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

}

Note, I do not have a broadcast receiver, I'm not quite sure how to use it so any examples would be very helpful.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

笑梦风尘 2024-12-09 20:49:32

您可以发布所有 UpdateLocation.class 吗?它需要扩展BroadcastReceiver,以便这可能是您的问题所在。

至于你的闹钟,如果它设置为每 xx 分钟响一次,没有结束,你最好使用 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), UPDATE_TIME * 60000,endingIntent); 定期重置闹钟。


编辑1

关于将 PendingIntent 放入静态函数中以便于访问,它可以是这样的:

public static PendingIntent getPendingIntent(int update_time) {
    Intent setAlarm = new Intent(this.getBaseContext(), UpdateLocation.class);
    PendingIntent pendingIntent = PendingIntent.getService(this.getBaseContext(),
                                                           0, setAlarm, 0)
    return pendingIntent;
}

然后您可以使用 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis) 设置闹钟(), UPDATE_TIME * 60000, MyClass.getPendingIntent());

Could you possibly post all of your UpdateLocation.class? It needs to extend BroadcastReceiver so that may be where your problem lies.

As for your alarm, if it's being set to go off every xx minutes without end, you're better off using alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), UPDATE_TIME * 60000, pendingIntent); to have your alarm reset on a regular basis.


Edit 1

Regarding putting the PendingIntent into a static function for easy access, it could go something like this:

public static PendingIntent getPendingIntent(int update_time) {
    Intent setAlarm = new Intent(this.getBaseContext(), UpdateLocation.class);
    PendingIntent pendingIntent = PendingIntent.getService(this.getBaseContext(),
                                                           0, setAlarm, 0)
    return pendingIntent;
}

And then you can set your alarm with alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), UPDATE_TIME * 60000, MyClass.getPendingIntent());

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文