如何使用AlarmManager触发报警?

时间:2013-11-20 19:37:38

标签: android data-binding service broadcastreceiver alarmmanager

在我的应用程序中,我有TextField和按钮。单击时,Service应从TextField启动读取值并触发AlarmManager。在金额秒之后,服务应通知BroadcastReceiver时间已经结束。我不知道我做错了什么。

活动告知服务并发送值。我可以看到Toast正确的秒数和Toast RUN,但我看不到吐司:'BroadcastReceiver'

服务:

    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;

        }

广播接收器:

public class MyReciver extends BroadcastReceiver {

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

清单:

<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>

1 个答案:

答案 0 :(得分:0)

尝试更改:

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

到:

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