10天學通Android開發(2-2)-核心組件Service創建

有些程序不需要交互,在後臺運行,並可長時間運行,不被操作系統殺死,這就是組件Service

 

  1. 聲明Service,新建classMyService,擴展自Service

  2. AndroidManifest中配置, Application中添加Serivice,選擇MySerivice

    實際添加了一行:

    <serviceandroid:name="MyService"></service>

  3. 添加二個按鈕,啓動Service和停止Service

     

    <Button

           android:id="@+id/btnStartService"

            android:layout_width="wrap_content"

           android:layout_height="wrap_content"

            android:text="啓動Servive"/>

     

        <Button

           android:id="@+id/btnStopService"

           android:layout_width="wrap_content"

           android:layout_height="wrap_content"

           android:text="停止Service" />

    4)代碼中添加二按鈕的定義:

private Button btnStartService,btnStopService;

  

    @Override

    protectedvoid onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        btnStartService=(Button) findViewById(R.id.btnStartService);

        btnStopService=(Button) findViewById(R.id.btnStopService);

        

       

}

5)添加兩按鈕的監聽事件,鼠標放紅線處,可自動生成:

(1)btnStartService.setOnClickListener(this);

(2)public class MainActivity extendsActionBarActivity implements OnClickListener

(3)@Override

         publicvoid onClick(View v) {

                  //TODO Auto-generated method stub

                   

                  }

6) 具體onClick內容:

@Override

         publicvoid onClick(View v) {

                  //TODO Auto-generated method stub

                   switch(v.getId()){

                   case R.id.btnStartService:

                   

                   break;

        case R.id.btnStopService:

                   

                   break;

        default:

                break;

                  }

7)啓動Service,需要定義Intent,:

private Intent serviceIntent;

並創建實例:

 serviceIntent=newIntent(this,MyService.class);

8) 在我們的Service重寫二方法,創建和銷燬:

@Override

         publicvoid onCreate(){

                  System.out.println("創建好了");

                  super.onCreate();

         }

        

         @Override

         publicvoid onDestroy(){

                  System.out.println("被銷燬了");

                  super.onDestroy();

         }      

9) 當前Activity銷燬,Service還會再運行,通過設置->應用程序->運行的程序或服務,可看到。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章