Android屏幕关闭时接收事件和意图

时间:2015-05-07 15:06:18

标签: android service

我需要一个服务来在屏幕关闭时处理事件,比如接收延迟消息(使用处理程序)和互联网连接状态更改。

服务是否有可能在没有永久使用PARTIAL_WAKE_LOCK的情况下获取这些信号,因为我不需要服务一直运行?

2 个答案:

答案 0 :(得分:1)

您需要BroadcastReceivers才能获得不同的状态。有关更多信息,请参阅Android文档

http://developer.android.com/reference/android/content/BroadcastReceiver.html

另外,例如,您可以在这里引用https://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/ 提供了示例链接中的一些片段

registerReceiver(
      new ConnectivityChangeReceiver(),
      new IntentFilter(
            ConnectivityManager.CONNECTIVITY_ACTION));

BroadcastReceiver实施

public class ConnectivityChangeReceiver
               extends BroadcastReceiver {

   @Override
   public void onReceive(Context context, Intent intent) {
      debugIntent(intent, "grokkingandroid");
   }

   private void debugIntent(Intent intent, String tag) {
      Log.v(tag, "action: " + intent.getAction());
      Log.v(tag, "component: " + intent.getComponent());
      Bundle extras = intent.getExtras();
      if (extras != null) {
         for (String key: extras.keySet()) {
            Log.v(tag, "key [" + key + "]: " +
               extras.get(key));
         }
      }
      else {
         Log.v(tag, "no extras");
      }
   }

}

正如StenSoft建议您可以将AlarmManager用于延迟消息或任何其他调度任务。我使用了以下示例及其工作

public class Alarm extends BroadcastReceiver 
{    
    @Override
    public void onReceive(Context context, Intent intent) 
    {   
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
        wl.acquire();

        // Put here YOUR code.
        Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

        wl.release();
    }

    public void SetAlarm(Context context)
    {
        AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, Alarm.class);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
    }
}

答案 1 :(得分:1)

对于延迟消息,请使用alarm

要在后台更改互联网连接,请使用WakefulBroadcastReceiver