1. 程式人生 > 實用技巧 >Android四大元件

Android四大元件

Activity

  Activity的生命週期onCreate();->onStart();->onResume();->onPause();->onStop();->Destroy();

Service

 如何執行服務

 1、建立一個類繼承Service

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}
2、在清單檔案中註冊這個服務
   <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true"></service>
3、執行服務
  Intent intent = new Intent(this, MyService.class);
  1、後臺執行服務(通過start方法啟動的service一旦服務開啟就跟呼叫者(開啟者)沒有任何關係了。開啟者退出了,開啟者掛了,服務還在後臺長期的執行,開啟者不能呼叫服務裡面的方法。)
  startService(intent);//開啟服務
  stopService(intent);//關閉服務

  2、bind執行服務(使用bind方法啟動的服務,則呼叫者掛了,服務也掛了,呼叫者可以呼叫服務中的方法)
  bindService(Intent,ServiceConnection,int);//開啟服務
  unbindService(ServiceConnection);//關閉服務
  



參考:心無止境_GX:Android四大元件