标签: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(); } }
标签:service
原文地址:http://blog.csdn.net/baidu_nod/article/details/38168427