7

I am creating alarm in Activity A & stopping/cancelling in another Activity B. I tried hard but no luck, below is my code :

MainAcitivity

public class MainActivity extends Activity 
{

    private PendingIntent pendingIntent;
    private static Context context;

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {

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

    Intent myIntent = new Intent(this, MyReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 12 * 60 * 60, pendingIntent); 

    } //end onCreate

}

MyReceiver

    public class MyReceiver extends BroadcastReceiver
    {

        @Override
         public void onReceive(Context context, Intent intent)
        {
           Intent service1 = new Intent(context, MyAlarmService.class);
           context.startService(service1);

         }

    }

MyAlarmService

public class MyAlarmService extends Service 

{
     private NotificationManager mManager;

     @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);

       mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
       Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);

       Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());

       intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

       PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
       notification.flags |= Notification.FLAG_AUTO_CANCEL;
       notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

       mManager.notify(0, notification);
    }

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

}

NextActivity

public class NextActivity extends Activity
{

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

           Intent intentt = new Intent(this, MyReceiver.class);
           PendingIntent pintent = PendingIntent.getBroadcast(this, 10, intentt, 0);
           AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
           stopService(intentt);
           alarm.cancel(pintent);
    }   
}

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />


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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.example.NextActivity"
            android:label="Next Screen">
        </activity>

        <service android:name=".MyAlarmService"
                 android:enabled="true" />

        <receiver android:name=".MyReceiver"/>

    </application>

</manifest>

It is still firing alarm, unable to stop/cancel after doing this.

halfer
  • 19,824
  • 17
  • 99
  • 186
VVB
  • 7,363
  • 7
  • 49
  • 83

3 Answers3

1

When creating your alarm, you use this PendingIntent:

Intent myIntent = new Intent(MainActivity.getAppContext(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 10, myIntent,0);

When you try to cancel it, you are using this PendingIntent:

Intent intentt = new Intent(MainActivity.getAppContext(), NextActivity.class);
PendingIntent pintent = PendingIntent.getService(this, 10, intentt, 0);

You need to use the same code to create the PendingIntent when you want to cancel the alarm. Use getBroadcast() instead of getService() and use MyReceiver.class instead of NextActivity.class.

Also, you don't need to save the application context in MainActivity. You can remove all this static stuff. You can just use this as the Context parameter when doing new Intent(Context, Thing.class)

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Thanks for reply, let me have a try – VVB Apr 16 '15 at 07:31
  • I tried as per your answer, but no luck still facing same issue – VVB Apr 16 '15 at 07:58
  • All looks fine. Please uninstall and reinstall your app. – David Wasser Apr 16 '15 at 08:54
  • Also, your call to `stopService()` won't work now, since you've changed `intentt` to contain a broadcast `Intent`. You will need to create another (different) `Intent` to pass to `stopService()` stop your service. You can also call `pintent.cancel()` to cancel the `PendingIntent` after you call `alarm.cancel()`, but this shouildn't be necessary. – David Wasser Apr 16 '15 at 08:56
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75371/discussion-between-vvb-and-david-wasser). – VVB Apr 16 '15 at 09:05
  • makes no sense. sorry explain please xactly what is hapenning Also, you've set this alarm so that it repeats every 12 * 60 * 60 milliseconds, that's every 43 seconds How do you know that the cancel isnt working? you can also check the pending alarms list using "adb shell dumpsys alarm" – David Wasser Apr 16 '15 at 09:21
  • You mean within short span of time Android OS fires number of alarms & those are getting fired in next few times though cancel call works. So simply I need to wait for something 30 minutes to check whether it is cancelled or not., am I right? – VVB Apr 16 '15 at 09:41
  • I don't know exactly. You could change the repeating interval so that you are sure that your alarm is being canceled. You should add logging to your `onReceive()` so you can determine when it is being called. You can check with `adb shell dumpsys alarm` to see if your alarm is still pending. You need to dig a bit more to see what is happening. How do you know it isn't working? – David Wasser Apr 16 '15 at 11:08
  • @David Wasser I have a similar use case here: https://stackoverflow.com/questions/61161676/android-cancel-alarm-and-pendingintent-in-different-activity I would appreciate any insights you could offer on how to solve. – AJW Apr 11 '20 at 23:08
0

Instead of calling methods as static way from which is not running for doing task use LocalBroadcastManager which is used for communicate between two component with in same process.

See following example :Android Program to Demonstrate Local BroadCastManager

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • Thanks for your reply, but can you please figure out problem in my code? – VVB Apr 16 '15 at 07:16
  • @VB: calling methods from one activity to another is also big problem so change current code with `LocalBroadCastManager` then i'm sure problem will solve – ρяσѕρєя K Apr 16 '15 at 07:18
  • @VVB: let me know if you have any issue in implementing `LocalBroadCastManager` – ρяσѕρєя K Apr 16 '15 at 07:20
  • Ok fine. Will implement it first & let you know if face any issues. – VVB Apr 16 '15 at 07:20
  • @VVB: In provided example link `Activityone` means `MainActivity` and `MainActivity` means `NextActivity` in your code – ρяσѕρєя K Apr 16 '15 at 07:24
  • Please see this : http://stackoverflow.com/questions/12113103/can-i-use-alarmmanager-with-localbroadcastmanager-on-android – VVB Apr 16 '15 at 07:24
  • @VVB: CommonsWare Sir answer if for different case. you can cancel/ stop `alarm` using `LocalBroadCastManager` – ρяσѕρєя K Apr 16 '15 at 07:26
  • Ok let me try with last comment – VVB Apr 16 '15 at 07:27
  • @VVB: just declare `AlarmManager alarmManager` outside `onCreate` method in MainActivity and call `alarmManager.cancel()` from `onReceive` to cancel Alarm – ρяσѕρєя K Apr 16 '15 at 07:27
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/75370/discussion-between-vvb-and--k). – VVB Apr 16 '15 at 08:59
  • can you please help me to solve this https://stackoverflow.com/questions/51542099/cant-stop-the-ringing-alarm-from-another-activity#51542099 @ρяσѕρєяK – Zhu Jul 26 '18 at 15:44
-1

OnButton Click Write below code , its working for me!!!!

            finish();


            Intent myIntent = new Intent(getBaseContext(),

                    MyBroadcastReceiver.class);

            PendingIntent pendingIntent
                    = PendingIntent.getBroadcast(getBaseContext(),
                    alaramid, myIntent, 0);

            AlarmManager alarmManager
                    = (AlarmManager) getSystemService(ALARM_SERVICE);

            alarmManager.cancel(pendingIntent);

//Navigate to your Activity
            Intent ii = new Intent(DisplayReminder.this, MenuActivity.class);
            ii.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(ii);

            finish();
Sathish Gadde
  • 1,453
  • 16
  • 28