天天看點

Android Api Demos登頂之路(五十四)Service LocalService Binding

這個demo示範了如何如何利用bindService的方式啟動一個本地服務,并實作與服務之間的通訊。

* 本例中所指的本地服務就是啟動服務的元件與服務處于同一個應用程序當中。

* 其實在上個例子中我們已經實作了這個demo這裡再和大家一起簡單回顧一下這個流程:

* 1.建立一個繼承Service的服務類

* 2.實作onBind方法,并傳回一個代理,這裡傳回服務本身的執行個體

* 3.實作服務的功能

* 4.在用戶端(activity)定義服務類的執行個體

* 5.建立與服務的連接配接,并實作兩個方法

* 6.使用bindService啟動服務

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/hello_world" />
    <Button 
        android:layout_marginTop="10dp"
        android:id="@+id/binding"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Binding Service"
        android:layout_gravity="center_horizontal"/>
    <Button 
        android:id="@+id/unbinding"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Unbinding Service"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>
           

LocalService

public class LocalService extends Service {
    private NotificationManager mNM;
    private static final int NOTIFICATION_ID = R.string.hello_world;

    @Override
    public void onCreate() {
        super.onCreate();
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        showNotification();
    }

    private void showNotification() {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, ,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        Notification.Builder builder=new Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher)
               .setTicker("服務已經啟動!")
               .setContentTitle("Local Service")
               .setContentText("This is the notification of a service")
               .setContentIntent(contentIntent)
               .setWhen(System.currentTimeMillis())
               .setDefaults(Notification.DEFAULT_ALL);
        Notification noti=builder.build();
        mNM.notify(NOTIFICATION_ID, noti);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 我們希望服務一直運作,當服務被意外殺死時仍然能夠重新啟動,是以設定傳回值為:START_STICKY
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mNM.cancel(NOTIFICATION_ID);
        Toast.makeText(this, "服務已經停止!", ).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    class MyBinder extends Binder {
        public LocalService getService() {
            return LocalService.this;
        }
    }

}
           

MainActivity

public class MainActivity extends Activity implements OnClickListener {
    private LocalService mService;
    private boolean isBound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button bt_binding = (Button) findViewById(R.id.binding);
        Button bt_unbinding = (Button) findViewById(R.id.unbinding);
        bt_binding.setOnClickListener(this);
        bt_unbinding.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.binding:
            doBind();
            break;
        case R.id.unbinding:
            doUnBind();
            break;
        }
    }

    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService=null;
            Toast.makeText(MainActivity.this, "與服務斷開連接配接!", ).show();
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService=((LocalService.MyBinder)service).getService();
            Toast.makeText(MainActivity.this, "與服務建立連接配接!", ).show();
        }
    };

    private void doUnBind() {
        if(isBound){
            unbindService(conn);
            isBound=false;
        }
    }

    private void doBind() {
        Intent intent=new Intent(this, LocalService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
        isBound=true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnBind();
    }
}
           

配置檔案

繼續閱讀