简体   繁体   中英

How to trigger alarm using AlarmManager?

In my app I have TextField and button. When clicked, Service should start read value from TextField and trigger AlarmManager. After amount seconds Service should inform BroadcastReceiver that time has finished. I don't know what I'm doing wrong.

Activity inform Service and send value. I can see Toast with correct number of second and toast RUN, but I can't see toast: 'BroadcastReceiver'

Service:

    public class MyService extends Service {

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            String data = (String) intent.getExtras().get("EXTRA_MESSAGE");
            int countTime = Integer.parseInt(data);
            Toast tosty = Toast.makeText(this, data + " sec", Toast.LENGTH_SHORT);
            tosty.show();

            Intent i = new Intent(this, MyReciver.class);
            PendingIntent pintent = PendingIntent.getService(this.getApplicationContext(), 1000, i, 0);
            AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (countTime * 1000), pintent);
            startService(i);
            Toast tost = Toast.makeText(getApplicationContext(),    
                "RUN!", Toast.LENGTH_SHORT);

            return Service.START_NOT_STICKY;

        }

BroadcastReceiver:

public class MyReciver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Toast tostyy = Toast.makeText(arg0, "BroadcastReciver!", Toast.LENGTH_LONG);
        tostyy.show();
    }
}

Manifest:

<service
    android:name="com.example.serwis.MyService"
    android:icon="@drawable/ic_launcher"
    android:label="@string/service_name" >
</service>

<receiver 
     android:name="com.example.serwis.MyReciver">
</receiver>

Try changing :

PendingIntent pintent = PendingIntent.getService(this.getApplicationContext(), 1000, i, 0);

to :

PendingIntent pintent = PendingIntent.getBroadcast(this.getApplicationContext(), 1000, i, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM