13

在我的活动课上

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AlarmManager alarmManager=(AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,System.currentTimeMillis(),2000, pendingIntent);

    }

还有我在alarmreciever 类中的onrecieve 函数

     @Override
     public void onReceive(Context context, Intent intent)
      {   
        //get and send location information
         System.out.println("fired");
      }

我正在使用nexus 4,kitkat版本。我没有看到每 2 分钟触发一次任何 onreceive 函数。nthg 正在发生......有什么帮助吗?谢谢你

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

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".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>
    <receiver
        android:name="com.example.AlarmExample"
        android:exported="false" >
    </receiver>
</application>
 </manifest>

我也只是把我的清单。...................................................

4

2 回答 2

16

在您的 setRepeating 函数中,您应该将 SystemClock.elapsedRealTime() 用于 ELAPSED_REALTIME_WAKEUP。此外,您需要将 2000 更改为 2*60*1000 以指定您的间隔时间。

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                          SystemClock.elapsedRealtime(),
                          2*60*1000, 
                          pendingIntent);

希望这可以帮助。

参考:ELAPSED_REALTIME_WAKEUP

编辑:在您的清单文件中,您的接收者名称中有错字。将“.AlarmReciever”更改为“.AlarmReceiver”。

<receiver
    android:name=".AlarmReceiver"
    android:exported="true" >
</receiver>
于 2014-10-26T13:30:24.380 回答
4

在您的代码中,您以这种方式设置警报

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            System.currentTimeMillis(),
            2000,
            pendingIntent);

每两分钟运行一次的间隔时间是错误的,你应该写:

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            0,
            1000 * 60 * 2,
            pendingIntent);

编辑

为您的未决意图设置标志PendingIntent.FLAG_UPDATE_CURRENT,看看它是否改变了任何东西。

PendingIntent alarmIntent = PendingIntent.getBroadcast(context,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
于 2014-10-26T13:25:35.520 回答