AlarmManager未在活动的oncreate中设置警报

时间:2015-02-25 08:12:22

标签: android

我想在acitivty的onCreate()方法上设置闹钟来调用Receiver来启动服务以从网站加载数据,但AlarmManager没有设置警报并在特定时间间隔内重复该警报这是我的代码。 这是MainActivity代码

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
                .findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // // Set up the drawer.
        // mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
        // (DrawerLayout) findViewById(R.id.drawer_layout));
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        // Set up the drawer.
        mNavigationDrawerFragment.setUp(R.id.navigation_drawer, mDrawerLayout);
        getFragmentManager().addOnBackStackChangedListener(
                new OnBackStackChangedListener() {

                    @Override
                    public void onBackStackChanged() {
                        BaseFragment fragment = getActiveFragment();
                        if (fragment != null) {
                            fragment.resetActionBarTitle();
                        }
                    }
                });

        setupAlarm();
    }

    private void setupAlarm() {
        // TODO Auto-generated method stub
        Intent i = new Intent(this, AlarmReciever.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
    }

这是AlarmReciever

public class AlarmReciever extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Log.d("onRecieve", "Reciever is executing");
        Intent i = new Intent(context, MyService.class);
        context.startService(i);

    }

这是我的Service

public class MyService extends Service {
    Map<String, String> map;
    ServerDetails serverDetails;

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.d("service Created", "service created");
        map = new HashMap<String, String>();

    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Log.d("service started", "service started");
        getStats();

    }

    private void getStats() {
        // TODO Auto-generated method stub
        System.out.print("get stats is executing");
        serverDetails = new ServerDetails(this);
        map.clear();
        Response.Listener<String> responseListner = new Response.Listener<String>() {

            @Override
            public void onResponse(String arg0) {
                // TODO Auto-generated method stub
                try {
                    JSONObject jobj = new JSONObject(arg0);
                    String result = jobj.getString("result");
                    if (result.contains("success")) {
                        map = new HashMap<String, String>();
                        map.put("result", result);
                        map.put("income_today", jobj.getString("income_today"));
                        map.put("income_thismonth",
                                jobj.getString("income_thismonth"));
                        map.put("income_thisyear",
                                jobj.getString("income_thisyear"));
                        map.put("tickets_open", jobj.getString("tickets_open"));
                        map.put("tickets_awaitingreply", String.valueOf(jobj
                                .getInt("tickets_awaitingreply")));
                        map.put("cancellations_pending",
                                jobj.getString("cancellations_pending"));
                        map.put("todoitems_due",
                                jobj.getString("todoitems_due"));
                        map.put("networkissues_open",
                                jobj.getString("networkissues_open"));
                        map.put("orders_pending",
                                jobj.getString("orders_pending"));
                        map.put("billableitems_uninvoiced",
                                jobj.getString("billableitems_uninvoiced")
                                        + " Overdue");
                    } else if (result.contains("error")) {

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

                }
                if (Integer.parseInt(map.get("tickets_awaitingreply")) > 0) {
                    showNotification();
                }
            }
        };

        StringRequest request = new StringRequest(Method.POST,
                serverDetails.getUrl(), responseListner,
                MyErrorListner.getListnerNoDialog(this)) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                // TODO Auto-generated method stub
                Map<String, String> map = serverDetails.getParameters();
                map.put("action", "getstats");
                Log.d("params map in service", map.toString());
                return map;
            }

        };
        AppController.getInstance().addToRequestQueue(request);

    }

    protected void showNotification() {
        // TODO Auto-generated method stub
        System.out.print("show notification is calling");
        Uri soundUri = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
        @SuppressWarnings("deprecation")
        Notification mNofification = new Notification.Builder(this)
                .setContentTitle("New Ticket")
                .setContentText("New Tickets Awaiting Reply")
                .setSmallIcon(R.drawable.ic_bill).setContentIntent(pIntent)
                .setSound(soundUri)
                /*
                 * .addAction(R.drawable.ic_bill, "View", pIntent) .addAction(0,
                 * "Remind", pIntent)
                 */.getNotification();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, mNofification);
    }

}

1 个答案:

答案 0 :(得分:0)

删除setAlarm()方法中的所有内容,然后只需粘贴此代码即可。

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

        if (PendingIntent.getService(this, 0, i, PendingIntent.FLAG_NO_CREATE) == null) {
            PendingIntent pendingIntent = PendingIntent.getService(this, 0, i,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 0,
                    AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
            Log.d("alarm", "alarm set successfully");
        } else {
            Log.d("alarm", "alarm already set");
        }

你必须检查警报是否已经存在。如果你不检查它,那么每当调用onCreate()时,setalarm将一次又一次地设置警报。此代码只会设置一次警报,您的服务将开始推送通知。