2

这是我的代码:

活动:

@Override
public void onCreate(Bundle savedInstanceState) {

...

Intent intent = new Intent(this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
    this.getApplicationContext(), 234324243, intent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
    + (5 * 1000), pendingIntent);

...
} 

广播接收器:

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent service = new Intent(context, StartNotificationService.class);

    context.startService(service);
}

服务:

public class StartNotificationService extends Service {

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

    this.intent = intent;
    showNotification();
}

private void showNotification() {
    Date date = new Date(pror.getFirstMillis());

    Log.i("date", date.toString());

    Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            createNotification(contentTitle, contentText, tickerText);

            pror.calculateVak();
            pror.setFirstMillis(pror.getNextVak());

            createStatusBarNotification(contentTitle, contentText, tickerText);
        }
    };
    timer.schedule(timerTask, date);
}

}

AndroidManifest

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
     android:icon="@drawable/icon"
    android:label="@string/app_name" >
    <activity android:name=".ShowSettingsActivity" />

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

    <activity android:name=".PreferencesActivity" android:label="@string/app_name">
   </activity>
    <activity
        android:label="@string/app_name"
        android:name=".VakActivity" >
        <intent-filter >
            <action android:name="android.intent.action.MAIN" />

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

当手机进入睡眠状态时,alarmManager 无法启动通知/服务。

如果我让我的手机处于“活动” - 解锁状态,则会在特定时间触发通知。

我在哪里犯错了?

4

1 回答 1

4

有两种方法可以接近它。

  1. 如果您所做的只是创建状态栏通知,那么只需在您的BroadcastReceiver
  2. 如果您需要在发出通知之前运行您的服务,并且您需要在设备处于睡眠状态时执行此操作,您需要获取WAKE_LOCK

因此,对于您需要的服务的课程主体中的方法2 :

PowerManager pm;
PowerManager.WakeLock wl;

然后在onCreate你需要:

pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();

然后在你的onDestroy你需要放:

wl.release();

我得到的所有这些信息PowerManager

于 2012-01-14T00:08:57.697 回答