編輯:關於Android編程
/**Service提供的方法*/ public interface IMyBinder { public void add(Bean bean); }
/** Service,主要處理網絡耗時等操作 */ public class MyService extends Service { /** 主要用handler傳遞一個操作 */ private Handler handler = new Handler(Looper.getMainLooper());// 默認為MainLooper // private BlockingQueuequeue; private WorkerThread thread; @Override public void onCreate() { queue = new ArrayBlockingQueue (5); thread = new WorkerThread(); //開啟線程 thread.start(); } @Override public IBinder onBind(Intent intent) { return new MyBinder(); } @Override public void onDestroy() { if (thread != null && !thread.isInterrupted()) { thread.quit(); } super.onDestroy(); } public interface DoWorkCallback { public void onUpdateProgress(int progress); public void onUpdateCompleted(); } public class MyBinder extends Binder implements IMyBinder { @Override public void add(Bean bean) { queue.add(bean); } } private class WorkerThread extends Thread { private boolean isQuited = false; @Override public void run() { while (true) { Bean bean = null; try { //該方法可能是阻塞的 bean = queue.take(); if (bean != null) { //傳遞一個操作,有MainLooper執行該runnable的run方法 handler.post(bean.runnable); } } catch (InterruptedException e) { if (!isQuited) { continue; } else { return; } } } } //退出線程 public void quit() { isQuited = true; queue.clear(); interrupt(); } } }
public class MainActivity extends Activity { private ProgressBar bar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bar = (ProgressBar) findViewById(R.id.bar); } public void click(View view) { Intent intent = new Intent(this, MyService.class); bindService(intent, connection, BIND_AUTO_CREATE); } private ServiceConnection connection = new ServiceConnection() { /** * 綁定完成,調用該方法,該方法運行在主線程中 */ @Override public void onServiceConnected(ComponentName name, IBinder service) { IMyBinder binder = (IMyBinder)service; System.out.println(onServiceConnected:+Thread.currentThread()); //doWork 接收一個url String 和一個回調接口,主要用於更新ui Bean bean = new Bean(); bean.runnable = new Runnable() { @Override public void run() { //TODO:耗時操作 } }; bean.callback = new DoWorkCallback() { @Override public void onUpdateProgress(int progress) { } @Override public void onUpdateCompleted() { } }; binder.add(bean); } @Override public void onServiceDisconnected(ComponentName name) { } }; }
public class Bean { public Runnable runnable; public DoWorkCallback callback; }
一、TabHost用法通常情況下我們會通過繼承TabActivity,調用getTabHost()獲取TabHost實例,下面是具體過程。TabHostActivity.
京東篩選更新了,很好,很炫酷。那什麼,我們也不差是吧,於是就有了這個demo。話不多說,先看圖,不想看代碼的朋友,直接點底部下demo。 圖1裡面呢,就兩點,彈出的Po
周末 特地把Android SwipeMenuListView(滑動菜單)的知識資料整理一番,以下是整理內容:SwipeMenuListView(滑動菜單)A swipe
使用數據庫實現對數據的存儲。 下面上一個小例子,寫日記。 效果如下: 當LIstView中沒有數據顯示時,我們需要告訴用戶沒有數據.