<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    瘋狂

    STANDING ON THE SHOULDERS OF GIANTS
    posts - 481, comments - 486, trackbacks - 0, articles - 1
      BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

    Android Service介紹

    Posted on 2009-11-04 16:04 瘋狂 閱讀(2132) 評(píng)論(0)  編輯  收藏 所屬分類: android
     

    本節(jié)內(nèi)容涉及到
    一 什么是Service
    如何使用Service
    Service的生命周期

    一 什么是Service

    Service,看名字就知道跟正常理解的“服務(wù)”差不多,后臺(tái)運(yùn)行,可交互這樣的一個(gè)東西。它跟Activity的級(jí)別差不多,但是他不能自己運(yùn)行,需要通過(guò)某一個(gè)Activity或者其他Context對(duì)象來(lái)調(diào)用, Context.startService() 和 Context.bindService()。

    兩種啟動(dòng)Service的方式有所不同。這里要說(shuō)明一下的是如果你在Service的onCreate或者onStart做一些很耗時(shí)間的事情,最好在 Service里啟動(dòng)一個(gè)線程來(lái)完成,因?yàn)?strong style="color: black; background-color: rgb(160,255,255)">Service是跑在主線程中,會(huì)影響到你的UI操作或者阻塞主線程中的其他事情。

    什么時(shí)候需要Service呢?比如播放多媒體的時(shí)候用戶啟動(dòng)了其他Activity這個(gè)時(shí)候程序要在后臺(tái)繼續(xù)播放,比如檢測(cè)SD卡上文件的變化,再或者在后臺(tái)記錄你地理信息位置的改變等等,總之服務(wù)嘛,總是藏在后頭的。

     

    如何使用Service

    那接下來(lái)用代碼來(lái)說(shuō)明一下怎么使用Service,這里我們要講的是Local Service也就是你自己的一個(gè)Service, 你也可以操作別的應(yīng)用程序的service如果它允許你那么去做的話,這就設(shè)計(jì)到一個(gè)比較麻煩的東西interprocess communication (IPC),在不同的進(jìn)程中通信的機(jī)制,這個(gè)我自己也還沒(méi)有用過(guò),等用了以后再跟大伙說(shuō)說(shuō),通常情況下Local的就夠用啦。

    跟Activity一樣首先你要寫一個(gè)類繼承自android.app.Service,在這里我叫他TestService
    代碼如下:

    package com.haric.tutorial;

    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    import android.util.Log;

    public class TestService extends Service {
    private static final String TAG = "TestService";
    private NotificationManager _nm;

    @Override
    public IBinder onBind(Intent i) {
    Log.e(TAG, "============> TestService.onBind");
    return null;
    }

    public class LocalBinder extends Binder {
    TestService getService() {
    return TestService.this;
    }
    }

    @Override
    public boolean onUnbind(Intent i) {
    Log.e(TAG, "============> TestService.onUnbind");
    return false;
    }

    @Override
    public void onRebind(Intent i) {
    Log.e(TAG, "============> TestService.onRebind");
    }

    @Override
    public void onCreate() {
    Log.e(TAG, "============> TestService.onCreate");
    _nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();
    }

    @Override
    public void onStart(Intent intent, int startId) {
    Log.e(TAG, "============> TestService.onStart");
    }

    @Override
    public void onDestroy() {
    _nm.cancel(R.string.service_started);
    Log.e(TAG, "============> TestService.onDestroy");
    }

    private void showNotification() {
    Notification notification = new Notification(R.drawable.face_1,
    "Service started", System.currentTimeMillis());

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
    new Intent(this, TestServiceHolder.class), 0);

    // must set this for content view, or will throw a exception
    notification.setLatestEventInfo(this, "Test Service",
    "Service started", contentIntent);

    _nm.notify(R.string.service_started, notification);
    }
    }

    其中用到Notification是為了明顯地表明Service存活的狀態(tài),跟demo的code學(xué)過(guò)來(lái)的,這樣看上去直觀一點(diǎn),更多關(guān)于Notification的內(nèi)容以后UI部分來(lái)寫吧,現(xiàn)在就知道怎么使用就好了。

    @Override
    public void onCreate() {
    Log.e(TAG, "============> TestService.onCreate");
    _nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();
    }

    像這樣,我在Service的幾個(gè)生命周期函數(shù)中加了打印log的語(yǔ)句,方便測(cè)試。

     

    public class LocalBinder extends Binder {
    TestService getService() {
    return TestService.this;
    }
    }

    這個(gè)方法是為了讓調(diào)用者得到這個(gè)Service并操作它。
    Service本身就這樣簡(jiǎn)單了,你需要做什么就在onCreate和onStart里做好了,起個(gè)線程什么的。

    再看一下它的調(diào)用者,TestServiceHolder

    package com.haric.tutorial;

    import android.app.Activity;
    import android.content.ComponentName;
    import android.content.Context;
    import android.content.Intent;
    import android.content.ServiceConnection;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.Toast;

    public class TestServiceHolder extends Activity {
    private boolean _isBound;
    private TestService _boundService;

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_service_holder);
    setTitle("Service Test");

    initButtons();
    }

    private ServiceConnection _connection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
    _boundService = ((TestService.LocalBinder)service).getService();

    Toast.makeText(TestServiceHolder.this, "Service connected",
    Toast.LENGTH_SHORT).show();
    }

    public void onServiceDisconnected(ComponentName className) {
    // unexpectedly disconnected,we should never see this happen.
    _boundService = null;
    Toast.makeText(TestServiceHolder.this, "Service connected",
    Toast.LENGTH_SHORT).show();
    }
    };

    private void initButtons() {
    Button buttonStart = (Button) findViewById(R.id.start_service);
    buttonStart.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
    startService();
    }
    });

    Button buttonStop = (Button) findViewById(R.id.stop_service);
    buttonStop.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
    stopService();
    }
    });

    Button buttonBind = (Button) findViewById(R.id.bind_service);
    buttonBind.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
    bindService();
    }
    });

    Button buttonUnbind = (Button) findViewById(R.id.unbind_service);
    buttonUnbind.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
    unbindService();
    }
    });
    }

    private void startService() {
    Intent i = new Intent(this, TestService.class);
    this.startService(i);
    }

    private void stopService() {
    Intent i = new Intent(this, TestService.class);
    this.stopService(i);
    }

    private void bindService() {
    Intent i = new Intent(this, TestService.class);
    bindService(i, _connection, Context.BIND_AUTO_CREATE);
    _isBound = true;
    }

    private void unbindService() {
    if (_isBound) {
    unbindService(_connection);
    _isBound = false;
    }
    }
    }

    這里可以看到兩種啟動(dòng)方法,start和bind,當(dāng)然也是通過(guò)intent調(diào)用的,在intent中指明指定要啟動(dòng)的Service的名字,stop也一樣

    private void startService() {
    Intent i = new Intent(this, TestService.class);
    this.startService(i);
    }

    private void stopService() {
    Intent i = new Intent(this, TestService.class);
    this.stopService(i);
    }

    對(duì)于bind的話,需要一個(gè)ServiceConnection對(duì)象

    private ServiceConnection _connection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
    _boundService = ((TestService.LocalBinder)service).getService();

    Toast.makeText(TestServiceHolder.this, "Service connected",
    Toast.LENGTH_SHORT).show();
    }

    public void onServiceDisconnected(ComponentName className) {
    // unexpectedly disconnected,we should never see this happen.
    _boundService = null;
    Toast.makeText(TestServiceHolder.this, "Service connected",
    Toast.LENGTH_SHORT).show();
    }
    };

    用來(lái)把Activity和特定的Service連接在一起,共同存亡,具體的生命周期細(xì)節(jié)下一段來(lái)講。


    Service的生命周期

    Service的生命周期方法比Activity少一些,只有onCreate, onStart, onDestroy
    我們有兩種方式啟動(dòng)一個(gè)Service,他們對(duì)Service生命周期的影響是不一樣的。


    1 通過(guò)startService

        Service會(huì)經(jīng)歷 onCreate -> onStart
       stopService的時(shí)候直接onDestroy

       如果是調(diào)用者(TestServiceHolder)自己直接退出而沒(méi)有調(diào)用stopService的
       話,Service會(huì)一直在后臺(tái)運(yùn)行。
       下次TestServiceHolder再起來(lái)可以stopService。

     

    2 通過(guò)bindService   

        Service只會(huì)運(yùn)行onCreate, 這個(gè)時(shí)候 TestServiceHolder 和TestService綁定在一起

       TestServiceHolder 退出了,Srevice就會(huì)調(diào)用onUnbind->onDestroyed
       所謂綁定在一起就共存亡了。

     

    那有同學(xué)問(wèn)了,要是這幾個(gè)方法交織在一起的話,會(huì)出現(xiàn)什么情況呢?
    一個(gè)原則是Service的onCreate的方法只會(huì)被調(diào)用一次,就是你無(wú)論多少次的startService又 bindService,Service只被創(chuàng)建一次。如果先是bind了,那么start的時(shí)候就直接運(yùn)行Service的onStart方法,如果先 是start,那么bind的時(shí)候就直接運(yùn)行onBind方法。如果你先bind上了,就stop不掉了,對(duì)啊,就是stopService不好使了,只 能先UnbindService, 再StopService,所以是先start還是先bind行為是有區(qū)別的。

    看起來(lái)情況很多,不過(guò)我會(huì)把這次的代碼包括上回Activity生命周期的研究代碼都貼上了,希望你喜歡!大家有興趣可以回去點(diǎn)點(diǎn)按鈕看看log,多看幾遍就知道了。

    轉(zhuǎn)載自:http://hi.baidu.com/weiyousheng/blog/item/b82f228bb1cdaf1ac9fc7a40.html

    主站蜘蛛池模板: 真人做人试看60分钟免费视频| 免费91麻豆精品国产自产在线观看| 1024免费福利永久观看网站| 亚洲AV无码1区2区久久| 中文字幕免费人成乱码中国| 亚洲美女在线国产| www.xxxx.com日本免费| 国产大片91精品免费看3| 激情无码亚洲一区二区三区| 国产男女猛烈无遮档免费视频网站| 亚洲精品无码少妇30P| 国产成人在线免费观看| 羞羞视频免费网站含羞草| 亚洲A∨精品一区二区三区| 羞羞视频在线观看免费| 亚洲av伊人久久综合密臀性色| 国产一二三四区乱码免费| 亚洲综合一区二区精品导航| 久久久久免费看成人影片| 亚洲伊人久久精品| 女人18毛片特级一级免费视频| 亚洲国产欧美国产综合一区| 日韩视频免费在线| 黄色视频在线免费观看| 亚洲天天在线日亚洲洲精| 久久久久av无码免费网| 亚洲hairy多毛pics大全| 久久乐国产精品亚洲综合| 99re热精品视频国产免费| 亚洲欧美日韩中文字幕一区二区三区| 四虎在线播放免费永久视频| 在线观看黄片免费入口不卡| 亚洲系列国产精品制服丝袜第| 日韩视频免费一区二区三区| 99精品视频在线观看免费| 亚洲中字慕日产2020| 波多野结衣免费视频观看| 98精品全国免费观看视频| 污视频网站在线观看免费| 精品亚洲成AV人在线观看| 国产jizzjizz视频全部免费|