【问题标题】:How to trigger alarm using AlarmManager?如何使用 AlarmManager 触发警报?
【发布时间】:2013-11-20 19:37:38
【问题描述】:

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

Activity 通知 Service 并发送值。我可以看到具有正确秒数和 toast RUN 的 Toast,但我看不到 toast: '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>

【问题讨论】:

    标签: android data-binding service broadcastreceiver alarmmanager


    【解决方案1】:

    尝试改变:

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

    到:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多