用IntentService写一个应用切到后台也正常运行的Service

IntentService的官方解释:

IntentService is a base class forServices that handle asynchronous requests (expressed asIntents) on demand. Clients send requests throughstartService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work


意思是IntentService在onHandleIntent中执行的操作不会阻碍UI线程,如果任务完成了,它会自动停止


写一个例子:

public class IntentServiceTest extends IntentService {

	private static volatile PowerManager.WakeLock systemLock = null;
	private static final String LOCK_NAME = "IntentServiceTest SyncService";
	private static final String SERVICE_NAME 	= "SyncService";
	
	public IntentServiceTest() {
		super(SERVICE_NAME);
	}
	
	public IntentServiceTest(String name) {
		super(name);
	}

	public static void scheduleUpdate(Context context,Class<IntentServiceTest> clsService) {
		try {
			final PowerManager.WakeLock lock = getLock(context
					.getApplicationContext());
			lock.acquire();
			Intent intent = new Intent(context, clsService);
			context.startService(intent);
		} catch (Throwable t) {
			System.out.println("===t="+t);
		}
	}

	private static synchronized PowerManager.WakeLock getLock(Context context) {
		if (systemLock == null) {
			try {
				PowerManager mgr = (PowerManager) context
						.getSystemService(Context.POWER_SERVICE);
				systemLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
						LOCK_NAME);
				systemLock.setReferenceCounted(true);
			} catch (Throwable t) {
			}
		}
		return systemLock;
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		try {
			System.out.println("==============do something");
		} catch (Throwable t) {
		} finally {
			try {
				final PowerManager.WakeLock lock = getLock(getApplicationContext());
				if (lock.isHeld()) {
					lock.release();
				}
			} catch (Throwable t) {
			}
		}
	}

}


我们写一个类来启动它:
public class PollingClass {

	private static PollingClass sInstance;

	private PollingClass() {
	}

	private static EventReceiver eventHandler;

	private static class EventReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
			} else if (intent.getAction().equals(
					ConnectivityManager.CONNECTIVITY_ACTION)) {
			}
		}

		private void register(Context context) {
			IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
			filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
			context.registerReceiver(this, filter);
		}
	}
	
	public void handleEvent(Context context, int eventId) {	
		performUpdate(context);
		scheduleTimer(context, 2000);
	}
	
	private void performUpdate(Context context) {
		IntentServiceTest.scheduleUpdate(context, IntentServiceTest.class);
	}

	public static synchronized PollingClass getInstance(Context context) {
		if (sInstance == null) {
			sInstance = new PollingClass();
			eventHandler = new EventReceiver();
			eventHandler.register(context);
		}
		return sInstance;
	}
	
	private static synchronized void scheduleTimer(Context context, long timeout){  
    	final long NPT = SystemClock.elapsedRealtime() + timeout;    	
    	Intent alarmIntent = new Intent(context, RepeatingAlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);                    
    	AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    	alarmMgr.cancel(pendingIntent);
    	alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, (long)NPT, pendingIntent);
    }
	

}

在Menufest里注册一个receive:
public class RepeatingAlarmReceiver extends BroadcastReceiver {
	private static final String TAG = "[RC]RepeatingAlarmReceiver";		

    @Override
    public void onReceive(final Context context, final Intent intent) {
    	System.out.println("===============Repeate receiver");
    	PollingClass.getInstance(context).handleEvent(context, 0);
    }

	
}

然后在activity中执行:PollingClass.getInstance(this).handleEvent(this, 0);

这里用到PowerManager:
newWakeLock(int flags, String tag);//取得相应层次的锁


flags参数说明:

PARTIAL_WAKE_LOCK :保持CPU 运转,屏幕和键盘灯是关闭的。
SCREEN_DIM_WAKE_LOCK :保持CPU 运转,允许保持屏幕显示但有可能是灰的,关闭键盘灯
SCREEN_BRIGHT_WAKE_LOCK :保持CPU 运转,保持屏幕高亮显示,关闭键盘灯
FULL_WAKE_LOCK :保持CPU 运转,保持屏幕高亮显示,键盘灯也保持亮度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值