Android 警报管理器无法工作

发布于 2024-11-30 02:33:13 字数 5855 浏览 3 评论 0原文

我的代码已经实现了警报管理器示例(其他问题的代码),但是,我的alarmReceiver(扩展BroadcastReceiver)不起作用;我不知道我的 MainActivity 没有触发意图,或者我的alarmReceiver 没有注册好。

所以我的alarmService也不工作(因为接收器不工作)。

我已经在我的manifest.xml 中写入了权限。

这是相关的代码。希望有人可以帮助我解决这个问题。多谢。


getBox.java


 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.getbox);


    /// 
    Intent intent = new Intent(getBox.this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBox.this, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
    Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

AlarmReceiver.java


 public class AlarmReceiver extends BroadcastReceiver {
  @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("ALARM_RECEIVER", "WORKING!!!");
        notificationStatus(context);

    }
    private void notificationStatus(Context context) {
        final NotificationManager mNotificationManager = (NotificationManager) 
                context.getSystemService(Context.NOTIFICATION_SERVICE);
                final int icon = R.drawable.icon;
        final CharSequence tickerText = context.getString(R.string.app_name);
        final long when = System.currentTimeMillis();
        final Notification notification = new Notification(icon, "ALARM_TEXT_1", when);
        final Intent notificationIntent = new Intent(context.getApplicationContext(),   getBox.class);
        final PendingIntent contentIntent = PendingIntent.getActivity(
                context.getApplicationContext(), 0, notificationIntent, 0);
                notification.setLatestEventInfo(context, tickerText, "ALARM_TEXT_2", contentIntent);
        mNotificationManager.notify(1, notification);
    }
}

AlarmService.java


 public class AlarmService extends WakefulIntentService {
  public AlarmService() {
    super("AlarmService");
  }

  @Override
  protected void doWakefulWork(Intent intent) {
    File log=new File(Environment.getExternalStorageDirectory(),
                      "AlarmLog.txt");
    Log.d("ALARM_SERVICE", "WORKING");
    try {
      BufferedWriter out=new BufferedWriter(
                            new FileWriter(log.getAbsolutePath(),
                                            log.exists()));

      out.write(new Date().toString());
      out.write("\n");
      out.close();

    }
    catch (IOException e) {
      Log.e("AppService", "Exception appending to log file", e);
    }
  }
}

OnBootReceiver.java


 public class OnBootReceiver extends BroadcastReceiver {
  private static final int PERIOD=3000;   // 3 sec

  @Override
  public void onReceive(Context context, Intent intent) {
    AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i=new Intent(context, AlarmReceiver.class);
    PendingIntent pi=PendingIntent.getBroadcast(context, 0,
                                              i, 0);

    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                      SystemClock.elapsedRealtime()+60000,
                      PERIOD,
                      pi);
  }
}

WakefulIntentService.java


 abstract public class WakefulIntentService extends IntentService {
  abstract void doWakefulWork(Intent intent);

  public static final String LOCK_NAME_STATIC="com.commonsware.android.syssvc.AppService.Static";
  private static PowerManager.WakeLock lockStatic=null;

  public static void acquireStaticLock(Context context) {
    getLock(context).acquire();
  }

  synchronized private static PowerManager.WakeLock getLock(Context context) {
    if (lockStatic==null) {
      PowerManager mgr=(PowerManager)context.getSystemService(Context.POWER_SERVICE);

      lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                            LOCK_NAME_STATIC);
      lockStatic.setReferenceCounted(true);
    }

    return(lockStatic);
  }

  public WakefulIntentService(String name) {
    super(name);
  }

  @Override
  final protected void onHandleIntent(Intent intent) {
    try {
      doWakefulWork(intent);
    }
    finally {
      getLock(this).release();
    }
  }
}

Manifest.xml

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:screenOrientation="portrait" android:name=".Mail"></activity>
    <activity android:screenOrientation="portrait" android:name=".getBox">
    </activity>
    <activity android:screenOrientation="portrait" android:name=".mainPage"></activity>
    <activity android:screenOrientation="portrait" android:name=".sendBox"></activity>        
    <activity android:screenOrientation="portrait" android:name=".main" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <provider android:name=".DataProvider" android:authorities="com.fleax.vocalclip.dataprovider" />
<receiver android:name=".OnBootReceiver">
     <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED" />
     </intent-filter>
</receiver>
<receiver android:name=".AlarmReceiver"></receiver>
<service android:name=".AlarmService"></service>
</application

My code has implemented the Alarm Manager Example(other question's code), however, my alarmReceiver(extends BroadcastReceiver) is not working; I don't know if my
MainActivity is not firing the intent or my alarmReceiver is not registered well.

So my alarmService is not working either(since Receiver is not working).

And I had wrote the permission, in my manifest.xml.

Here is the code related. Hope some one could help me with this problem. Thanks a lot.


getBox.java


 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.getbox);


    /// 
    Intent intent = new Intent(getBox.this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBox.this, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
    Toast.makeText(this, "Alarm set", Toast.LENGTH_LONG).show();

AlarmReceiver.java


 public class AlarmReceiver extends BroadcastReceiver {
  @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("ALARM_RECEIVER", "WORKING!!!");
        notificationStatus(context);

    }
    private void notificationStatus(Context context) {
        final NotificationManager mNotificationManager = (NotificationManager) 
                context.getSystemService(Context.NOTIFICATION_SERVICE);
                final int icon = R.drawable.icon;
        final CharSequence tickerText = context.getString(R.string.app_name);
        final long when = System.currentTimeMillis();
        final Notification notification = new Notification(icon, "ALARM_TEXT_1", when);
        final Intent notificationIntent = new Intent(context.getApplicationContext(),   getBox.class);
        final PendingIntent contentIntent = PendingIntent.getActivity(
                context.getApplicationContext(), 0, notificationIntent, 0);
                notification.setLatestEventInfo(context, tickerText, "ALARM_TEXT_2", contentIntent);
        mNotificationManager.notify(1, notification);
    }
}

AlarmService.java


 public class AlarmService extends WakefulIntentService {
  public AlarmService() {
    super("AlarmService");
  }

  @Override
  protected void doWakefulWork(Intent intent) {
    File log=new File(Environment.getExternalStorageDirectory(),
                      "AlarmLog.txt");
    Log.d("ALARM_SERVICE", "WORKING");
    try {
      BufferedWriter out=new BufferedWriter(
                            new FileWriter(log.getAbsolutePath(),
                                            log.exists()));

      out.write(new Date().toString());
      out.write("\n");
      out.close();

    }
    catch (IOException e) {
      Log.e("AppService", "Exception appending to log file", e);
    }
  }
}

OnBootReceiver.java


 public class OnBootReceiver extends BroadcastReceiver {
  private static final int PERIOD=3000;   // 3 sec

  @Override
  public void onReceive(Context context, Intent intent) {
    AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent i=new Intent(context, AlarmReceiver.class);
    PendingIntent pi=PendingIntent.getBroadcast(context, 0,
                                              i, 0);

    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                      SystemClock.elapsedRealtime()+60000,
                      PERIOD,
                      pi);
  }
}

WakefulIntentService.java


 abstract public class WakefulIntentService extends IntentService {
  abstract void doWakefulWork(Intent intent);

  public static final String LOCK_NAME_STATIC="com.commonsware.android.syssvc.AppService.Static";
  private static PowerManager.WakeLock lockStatic=null;

  public static void acquireStaticLock(Context context) {
    getLock(context).acquire();
  }

  synchronized private static PowerManager.WakeLock getLock(Context context) {
    if (lockStatic==null) {
      PowerManager mgr=(PowerManager)context.getSystemService(Context.POWER_SERVICE);

      lockStatic=mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                            LOCK_NAME_STATIC);
      lockStatic.setReferenceCounted(true);
    }

    return(lockStatic);
  }

  public WakefulIntentService(String name) {
    super(name);
  }

  @Override
  final protected void onHandleIntent(Intent intent) {
    try {
      doWakefulWork(intent);
    }
    finally {
      getLock(this).release();
    }
  }
}

Manifest.xml

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:screenOrientation="portrait" android:name=".Mail"></activity>
    <activity android:screenOrientation="portrait" android:name=".getBox">
    </activity>
    <activity android:screenOrientation="portrait" android:name=".mainPage"></activity>
    <activity android:screenOrientation="portrait" android:name=".sendBox"></activity>        
    <activity android:screenOrientation="portrait" android:name=".main" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <provider android:name=".DataProvider" android:authorities="com.fleax.vocalclip.dataprovider" />
<receiver android:name=".OnBootReceiver">
     <intent-filter>
          <action android:name="android.intent.action.BOOT_COMPLETED" />
     </intent-filter>
</receiver>
<receiver android:name=".AlarmReceiver"></receiver>
<service android:name=".AlarmService"></service>
</application

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

叹沉浮 2024-12-07 02:33:13
  1. 未定义操作的广播待定意图对我来说并不常见。

  2. AlarmManager 可以使用服务挂起意图。

    <前><代码>/* (...) */
    意图 i = new Intent(context, AlarmService.class);
    PendingIntent pi = PendingIntent.getService(上下文, 0, i, 0);
    /* (...) */

  1. Broadcast Pending Intent with no action defined is not very common for me.

  2. AlarmManager can use an Service Pending Intent.

    /* (...) */
    Intent i = new Intent(context, AlarmService.class);
    PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
    /* (...) */
    
三月梨花 2024-12-07 02:33:13
public void scheduleAlarm(View V)
{
    // time at which alarm will be scheduled here alarm is scheduled at 1 day from current time, 
    // we fetch  the current time in milliseconds and added 1 day time
    // i.e. 24*60*60*1000= 86,400,000   milliseconds in a day       
    Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;

    // create an Intent and set the class which will execute when Alarm triggers, here we have
    // given AlarmReciever in the Intent, the onRecieve() method of this class will execute when

    Intent intentAlarm = new Intent(this, AlarmReciever.class);

    //Get the Alarm Service
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //set the alarm for particular time
    alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
    Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();

}

警报接收器类

public class AlarmReciever extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        // TODO Auto-generated method stub                                  
        // Your Code     When Alarm willl trigger                             
    }
}   
public void scheduleAlarm(View V)
{
    // time at which alarm will be scheduled here alarm is scheduled at 1 day from current time, 
    // we fetch  the current time in milliseconds and added 1 day time
    // i.e. 24*60*60*1000= 86,400,000   milliseconds in a day       
    Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;

    // create an Intent and set the class which will execute when Alarm triggers, here we have
    // given AlarmReciever in the Intent, the onRecieve() method of this class will execute when

    Intent intentAlarm = new Intent(this, AlarmReciever.class);

    //Get the Alarm Service
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //set the alarm for particular time
    alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1,  intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
    Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();

}

AlarmReciever Class

public class AlarmReciever extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        // TODO Auto-generated method stub                                  
        // Your Code     When Alarm willl trigger                             
    }
}   
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文