当前位置:首页 > 移动开发 > 移动开发

怎么写一个程序升级的service

优良自学吧提供怎么写一个程序升级的service,如何写一个程序升级的service这个升级可以在程序启动时调用: 首先建立一个service的类:MyService extends Service,然后在menifest中声明: <service android:name=".MyService"><

如何写一个程序升级的service

这个升级可以在程序启动时调用:

首先建立一个service的类:MyService extends Service,然后在menifest中声明:

<service android:name=".MyService"></service>

这样来调用:

	Intent intent = new Intent();
	intent.setClass(MainActivity.this, MyService.class);
		
	<strong>startService(intent);  //不能用startActivity</strong>


这样会去执行Service中的onstart


public class MyService extends Service {

	/** thread to execute background task*/
	private Thread mThread = null;
	
	/** flag indicates if the service has been stopped*/
	private boolean mStopFlag = false;
	
	private static final int GET_UPGRADE_INFORMATION_COMPLETE = 202;
	
	/** Handler to get notify from thread*/
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GET_UPGRADE_INFORMATION_COMPLETE:
				System.out.println("=======notify need upgrade");
			default:
				break;
			}
		}
	};
	
	
	@Override
	public boolean onUnbind(Intent intent) {
		System.out.println("====service onUnbind");
		return super.onUnbind(intent);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		System.out.println("====service onBind");
		return null;
	}
	
	/**
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println("====service onCreate");
	}

	/**
	 * @see android.app.Service#onStart(android.content.Intent, int)
	 */
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		System.out.println("====service onstart");
		if(mThread == null){
			mThread = new UpgradeThread();
			mThread.start();
		}
	}
	
	private class UpgradeThread extends Thread{

		/**
		 * @see java.lang.Thread#run()
		 */
		@Override
		public void run() {
			super.run();
			//在这里写去服务端查看是否需要升级的逻辑
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			boolean ret = true;
			if(ret && !mStopFlag){
				Message msg = new Message();
				msg.what = GET_UPGRADE_INFORMATION_COMPLETE;
				mHandler.sendMessage(msg);
			}
		}
		
	}
	
	/* (non-Javadoc)
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		System.out.println("====ondestroy");
		mStopFlag = true;
		try {
			if (null != mThread && mThread.isAlive()) {
				try
				{
					mThread.stop();
				}
				catch (Exception e)
				{
				}
			}
			mThread = null;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
		System.gc();
	}

}




(本文来自互联网,不代表搜站(http://www.ylzx8.cn/)的观点和立场)
本站所有内容来自互联网,若本站收录的信息无意侵犯了贵司版权,请给我们来信(ylzx8cn@163.com),我们会及时处理和回复,谢谢