闹钟管理器和广播接收器没有停止。

4
我希望在多个特定日期和时间创建通知,这些日期和时间存储在数据库中。我可以在正确的日期和时间收到通知,但后来我注意到,我也随机收到了下一天的通知。每当我重新启动模拟器时,它们就会不断地出现。
因此,似乎我无法停止Alarm Manager或Broadcast Receiver。我尝试使用pendingIntent提供给AlarmManager的cancel方法,但无济于事。我还使用切换按钮来启用/禁用通知,但没有效果。
以下是我的代码。
MainActivity.java
PendingIntent pendingIntent;
    AlarmManager alarmManager;
    Button set, cancel;
    MTPAdapter db;
    ArrayList<TourPlan> arrDates;

    ToggleButton toggle;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        toggle = (ToggleButton) findViewById(R.id.toggleButton1);

                // This function fetched data from DB
        fetchDates();



        set = (Button) findViewById(R.id.the_button);
        cancel = (Button) findViewById(R.id.the_button_cancel);
        cancel.setEnabled(false);



        toggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                if (isChecked) {
                    Toast.makeText(getApplicationContext(), "Set",
                            Toast.LENGTH_SHORT).show();
                    setEvent();
                } else {
                    alarmManager.cancel(pendingIntent);
                    MyReceiver.stopService(getApplicationContext());
                }
            }
        });
    } // end onCreate

    public void setEvent() {

        for (int i = 0; i < arrDates.size(); i++) {
            // int id = arrDates.get().getId();

            int year = Integer.parseInt(arrDates.get(i).getYear());

            int month = Integer.parseInt(arrDates.get(i).getMonth());

            int date = Integer.parseInt(arrDates.get(i).getDate());

            int hour = Integer
                    .parseInt(firstStringer(arrDates.get(i).getTime()));
            Log.v("Hour : ", "" + hour);

            int minute = Integer.parseInt(stringer(arrDates.get(i).getTime()));
            Log.v("minute : ", "" + minute);
            int second = 00;
            startAlarm(i, year, month, date, hour, minute, second);
        }
    }

    public void startAlarm(int id, int year, int month, int date, int hour,
            int minute, int second) {
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.DAY_OF_MONTH, date);

        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        // calendar.set(Calendar.AM_PM, Calendar.PM);

        Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);

        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, id,
                myIntent, 0);

        alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(),
                pendingIntent);
    }


    }

MyAlarmService.java

public class MyAlarmService extends Service {


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

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    @SuppressWarnings("static-access")
    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);



        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("ISFA")
                .setStyle(
                        new NotificationCompat.BigTextStyle()
                                .bigText("Tour Planned for the Day"))
                .setContentText("You have planned a tour for today")
                .setAutoCancel(true);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

MyReceiver.java(广播接收器):


  public class MyReceiver extends BroadcastReceiver {

            @Override
            public void onReceive(Context context, Intent intent) {

                Intent service1 = new Intent(context, MyAlarmService.class);
                context.startService(service1);

            }

            public static void stopService(Context context) {
                Intent stopServiceIntent = new Intent(context, MyAlarmService.class);
                context.stopService(stopServiceIntent);
            }
        }

清单文件:

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

在应用程序标签中,
 <service
           android:name="com.example.brodcastalarm.MyAlarmService"
           android:enabled="true" />
   <!-- THE BROADCAST RECIEVER WHICH MANAGES THE BROADCAST FOR NOTIFICATION -->
            <receiver android:name="com.example.brodcastalarm.MyReceiver" >
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </receiver>

这是数据库结构。 我使用subString方法获取小时和分钟。

每次启动模拟器都被视为重新启动手机,因此这可能是导致服务和应用程序从头开始的原因! - Saqib
好的,我明白了。但是我设置了特定日期和时间的闹钟。为什么它们会在错误的时间和日期开始?这就是我无法理解的问题。此外,即使我切换到“关闭”状态,我也无法停止闹钟。因此,服务从未真正停止。 - Dhaval
这是用于从数据库获取日期的代码。数组是从数据库值填充的。我之前没有把它放在代码中,我应该在此之前明确说明。日期、月份和年份是存储在数据库中的独立字段。我已经更新了代码,并附上了数据库截图。 - Dhaval
1
要禁用您的闹钟管理器,您需要获取其实例并手动取消它,如下所示:AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE); Intent intent = new Intent(getBaseContext(), YourScheduleClass.class); PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); aManager.cancel(pIntent); - Saqib
好的,伙计。我会尝试这个解决方案并回复你。感谢指南。 - Dhaval
你的代码片段可行。将其作为答案发布,我会接受它。我成功地有效地终止了警报。谢谢。 - Dhaval
1个回答

2

警报管理器需要手动禁用,因此要这样做,请使用以下代码,它将禁用警报。

AlarmManager aManager = (AlarmManager) getSystemService(ALARM_SERVICE);         
Intent intent = new Intent(getBaseContext(), YourScheduleClass.class);      
PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent,              PendingIntent.FLAG_UPDATE_CURRENT);         
aManager.cancel(pIntent);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接