1. 子線程操作UI的三種方式
a. handler
b. runOnUiThread()
c. asyncTask
c.1 onPreExecute()
c.2 doInBackground(Params...)執行主要任務 調用publishProgress()
c.3 onProgressUpdate(Progress...)進行UI更新
c.4 onPostExecute(Result)
2. 服務的操作
a. 新建類繼承Service,重寫onBind方法,和其他邏輯操作方法onCreate onStartCommand onDestroy
b. 啓動和停止服務
Intent intent=newIntent(this,MyService.class);
startService(intent);
stopService(intent);
c. 綁定服務(用於服務和Activity之間進行聯繫)
c.1 在服務類中定義一個繼承Binder 的內部類 並在OnBind方法中返回定義的內部類對象
c.2 在Activity中bindService(intent,connection,BIND_AUTO_CREATE)解綁unbindService(connection);
c.3 這個connection是ServiceConnection的對象,類中實現的兩個方法onServiceDisconnected 和 onServiceConnected(在這個方法中拿到服務中定義的內部類對象,並進行所需的操作)
d. 服務的生命週期
e. 前臺服務(源碼)
public class LocalService extends Service { private NotificationManager mNM;
// 通知唯一的標識 private int NOTIFICATION = R.string.local_service_started;
public class LocalBinder extends Binder { LocalService getService() { return LocalService.this; } }
@Override public void onCreate() { mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar. showNotification(); }
@Override public int onStartCommand(Intent intent, int flags, int startId) { Log.i("LocalService", "Received start id " + startId + ": " + intent); return START_NOT_STICKY; }
@Override public void onDestroy() { mNM.cancel(NOTIFICATION); Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show(); }
@Override public IBinder onBind(Intent intent) { return mBinder; }
private final IBinder mBinder = new LocalBinder();
private void showNotification() { CharSequence text = getText(R.string.local_service_started);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, LocalServiceActivities.Controller.class), 0);
Notification notification = new Notification.Builder(this) .setSmallIcon(R.drawable.stat_sample) // the status icon .setTicker(text) // the status text .setWhen(System.currentTimeMillis()) // the time stamp .setContentTitle(getText(R.string.local_service_label)) // the label of the entry .setContentText(text) // the contents of the entry .setContentIntent(contentIntent) // The intent to send when the entry is clicked .build();
// Send the notification. mNM.notify(NOTIFICATION, notification); } } |