Android Service詳解(二)

來源:互聯網
上載者:User

標籤:android   service   

    Service中有四個重要函數:  

    public IBinder onBind(Intent arg0);    //必須實現,返回介面給Service    public void onCreate();                //Service建立時調用    public void onStart(Intent intent,int startId);//通過startService()會調用    public void onDestroy();                //銷毀時StopService()調用

 

通過StartActivity()函數啟動Service,當第一次調用時會分別調用onCreate()和onStart在();

之後只會調用onStart();

通過函數StopService()結束Service,會調用onDestroy();

調用BindService():當Service未建立時調用onCreate()和onBind();當建立了只調用onBind();

使用函數bindService()和函數unbindService()可以綁定和解除綁定

對已經綁定的Service調用bindService()無效,即多次調用bindService()和調用一次bindService()一樣。 unbindService()只能使用一次,即對於一個綁定的Service,只能調用一次unbindService(),多次調用會產生錯誤


該函數原型為:

bindService(Intent,ServiceConnection,BIND_AUTO_CREATE);

ServiceConnection是一個服務串連類,必須實現以下兩個函數:

public void onServiceConnected(ComponentName arg0, IBinder arg1)//串連成功時調用public void onServiceDisconnected(ComponentName arg0)        //串連失敗時調用

    樣本如下:

private ServiceConnection conn=new ServiceConnection() {    @Override    public void onServiceConnected(ComponentName arg0, IBinder arg1) {        // TODO Auto-generated method stub        Toast.makeText(MainActivity.this, "success", Toast.LENGTH_LONG).show();        Log.i("SERVICE","success");    }    @Override    public void onServiceDisconnected(ComponentName arg0) {        // TODO Auto-generated method stub        Toast.makeText(MainActivity.this, "errer", Toast.LENGTH_LONG);        Log.i("SERVICE","errer");    }

    

    

Service執行個體:

    MainActivity.java:

private ServiceConnection conn=new ServiceConnection() {    @Override    public void onServiceConnected(ComponentName arg0, IBinder arg1) {        // TODO Auto-generated method stub        Toast.makeText(MainActivity.this, "success", Toast.LENGTH_LONG).show();        Log.i("SERVICE","success");    }    @Override    public void onServiceDisconnected(ComponentName arg0) {        // TODO Auto-generated method stub        Toast.makeText(MainActivity.this, "errer", Toast.LENGTH_LONG);        Log.i("SERVICE","errer");    }};
protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    Button button1=(Button)this.findViewById(R.id.btn1);    Button button2=(Button)this.findViewById(R.id.btn3);    Button button3=(Button)this.findViewById(R.id.btn4);    Button button4=(Button)this.findViewById(R.id.btn5);    button1.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View arg0) {            // TODO Auto-generated method stub            startService(new Intent(MainActivity.this,NewService.class));        }    });    button2.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View arg0) {            // TODO Auto-generated method stub            stopService(new Intent(MainActivity.this,NewService.class));        }    });    button3.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View arg0) {            // TODO Auto-generated method stub            bindService(new Intent(MainActivity.this,NewService.class),conn,BIND_AUTO_CREATE);        }    });    button4.setOnClickListener(new OnClickListener() {        @Override        public void onClick(View arg0) {            // TODO Auto-generated method stub            unbindService(conn);        }    });}

NewService.java:

public class NewService extends Service {    @Override    public IBinder onBind(Intent arg0) {        // TODO Auto-generated method stub        Toast.makeText(NewService.this, "onBind", Toast.LENGTH_LONG).show();        Log.i("SERVICE","onbind");        return null;    }    public void onCreate() {        super.onCreate();        Log.i("SERVICE","oncreat");        Toast.makeText(NewService.this, "onCreat", Toast.LENGTH_LONG).show();    }    public void onStart(Intent intent,int startId) {        Log.i("SERVICE","onstart");        Toast.makeText(NewService.this, "onStart", Toast.LENGTH_LONG).show();    }    public void onDestroy() {        Log.i("SERVICE","ondestory");        Toast.makeText(NewService.this, "onDestory", Toast.LENGTH_LONG).show();    }}

Activity.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <Button android:id="@+id/btn1"         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="start"/>    <Button android:id="@+id/btn3"         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="stop"/>    <Button android:id="@+id/btn4"         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="bind"/>    <Button android:id="@+id/btn5"         android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="unbind"/>    </LinearLayout>

AndroidManifest.xml增加:

 <service android:name="com.example.new1.NewService"/>




本文出自 “無用大叔” 部落格,請務必保留此出處http://aslonely.blog.51cto.com/6552465/1616665

Android Service詳解(二)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.