Android回顧--(二十二) Service的初涉和Notification通知

Service服務(wù)

??Android四大金剛之一棺耍,不依賴與UI和組件,可以獨立的運行在后臺。

Service的使用:

一舒帮、startService
  1. 創(chuàng)建一個類繼承于Service
  2. 重寫Service里面的onStart或者onStartCommand,已經(jīng)onCreate陡叠、onBind玩郊、onDestory方法
public class MyService extends Service {
    public MyService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * 處理業(yè)務(wù)邏輯的地方
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
  1. 使用startService打開服務(wù)
        Intent intent = new Intent(MainActivity.this, MyService.class);
        startService(intent);
  1. 需要在mainifest中聲明
        <service android:name=".MyService"/>
  1. 關(guān)閉Service
stopService(intent)

Service的優(yōu)先級:Service的優(yōu)先級比不可見的Activity的優(yōu)先級高,比可見的Activity優(yōu)先級底枉阵。

二译红、BindService

??綁定模式下的Service會依賴于組件,非綁定模式下的Service不依賴于組件兴溜。

  1. 編寫一個類繼承于Service
public class MyBinderStartService extends Service{
    Binder binder=new MyBinder();
    public int number=0;
    public boolean isLooping=true;
  1. 在Service里面編寫一個類繼承于Binder
  2. 在Binder類里面編寫一個方法返回當前這個Service的實例:Service.this
public class MyBinder extends Binder{
    public MyBinderStartService getService(){
        return MyBinderStartService.this;
    }
}
  1. 在Service的onBind方法里面返回自定義的這個類的實例
@Override
public IBinder onBind(Intent intent) {
    Log.e("---------------------","onBind");
    return binder;
}
  1. 定義業(yè)務(wù)邏輯的方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("---------------------","onStartCommand");
    new Thread(new Runnable() {
        @Override
        public void run() {
            while (isLooping){
                try {
                    Thread.sleep(500);
                    Log.e("----------------------",(number++)+"");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
    return 0;
}
  1. 在需要使用這個Service的組件中來進行調(diào)用
    • 首先需要準備Intent
      Intent mIntent=new Intent(MainActivity.this, MyBinderStartService.class);
    • 編寫一個類實現(xiàn)于ServiceConnection這個類并且實現(xiàn)里面的onServiceConnected和onDisServiceConnected
    • 調(diào)用BindService(intent,MyServiceConn,flag)
/**
 * 連接那個Service
 */
private class MyServiceConn implements ServiceConnection{
    @Override
    public void onServiceConnected(ComponentName name, IBinder binder) {
        MyBinderStartService.MyBinder myBinder=(MyBinderStartService.MyBinder)binder;
        myBinderStartService = myBinder.getService();
        Log.e("---------------","綁定成功........");
    }

    /**
     * 綁定零食出現(xiàn)問題或者  被系統(tǒng)殺死才會調(diào)用這個方法
     * @param name
     */
    @Override
    public void onServiceDisconnected(ComponentName name) {
       Log.e("----------------","我被殺死...............");
    }
}

綁定Service

bindService(mIntent,myServiceConn,BIND_AUTO_CREATE);
  1. 在需要調(diào)用事件的地方調(diào)用Service方法侦厚。

注意:BindService這個方法是異步的,如果在綁定的同時立馬執(zhí)行調(diào)用方法拙徽,不會成功刨沦,BindService的stop方法是沒用的,當解除綁定時會調(diào)用onDestroy方法膘怕,Service就死了想诅。

三、IntentService

??也是一個Service岛心,在IntentService里面封裝了異步任務(wù)(不需要new線程)来破,在運行完所有任務(wù)之后會自動終止Service的運行。

IntentService的使用:

  1. 自定義一個類繼承于IntentService忘古,并重寫構(gòu)造函數(shù)
public class MyIntentSevice extends IntentService {

    public MyIntentSevice() {
        super("小子");
    }
  1. 重寫里面的onHandleIntent方法
    onHandleIntent:系統(tǒng)new好的異步任務(wù)的回調(diào)徘禁,可以完成耗時操作。
 /**
     * 必須重寫這個方法:系統(tǒng)給你new好的異步任務(wù)的回調(diào)
     * 這個里面可以完成那個耗時的操作
     * @param intent
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            Thread.sleep(5000);  //用睡眠來模擬那個耗時的操作
            Log.e("------------------",Thread.currentThread().getName());
            Log.e("---------------","我執(zhí)行完成了.....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
  1. 在mainifest中聲明
  2. 在Activity中打開服務(wù)
        Intent intent = new Intent(MainActivity.this, MyBindService.class);
        startService(intent);

Notification通知

  1. 通過NotificationManger獲取管理者對象
        NotificationManager mNotificationManager=null;
        //第一步:通過NotificationManager獲取那個管理者對象
        mNotificationManager= (android.app.NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
  1. 使用Notification的Builder獲取一個builder對象
Notification.Builder builder = new Notification.Builder(IntentServiceActivity.this);
  1. 通過Builder對象設(shè)置相應(yīng)的值
        //通過builder對象設(shè)置相應(yīng)的值
        mBuilder.setContentTitle("天氣預(yù)報");   //設(shè)置標題
        mBuilder.setContentText("城市的天氣預(yù)報正在掌握中...");  //設(shè)置那個提示的內(nèi)容
        mBuilder.setSmallIcon(R.mipmap.ic_launcher);    //設(shè)置前面的那個圖標
        mBuilder.setAutoCancel(true);   //點擊了那個通知之后那個通知是要消失的
  1. 顯示通知

        Notification mNotification=mBuilder.build();
        mNotificationManager.notify(34,mNotification);
  1. 可以通過id取消單個通知存皂,也可以通過cancelAll取消同一個通知管理者下的所有通知晌坤。
                mNotificationManager.cancel(34);
                mNotificationManager.cancelAll();
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末逢艘,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子骤菠,更是在濱河造成了極大的恐慌它改,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件商乎,死亡現(xiàn)場離奇詭異央拖,居然都是意外死亡,警方通過查閱死者的電腦和手機鹉戚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進店門鲜戒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人抹凳,你說我怎么就攤上這事遏餐。” “怎么了赢底?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵失都,是天一觀的道長。 經(jīng)常有香客問我幸冻,道長粹庞,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任洽损,我火速辦了婚禮庞溜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘碑定。我一直安慰自己流码,他們只是感情好,可當我...
    茶點故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布不傅。 她就那樣靜靜地躺著旅掂,像睡著了一般赏胚。 火紅的嫁衣襯著肌膚如雪访娶。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天觉阅,我揣著相機與錄音崖疤,去河邊找鬼。 笑死典勇,一個胖子當著我的面吹牛劫哼,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播割笙,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼权烧,長吁一口氣:“原來是場噩夢啊……” “哼眯亦!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起般码,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤妻率,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后板祝,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體宫静,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年券时,在試婚紗的時候發(fā)現(xiàn)自己被綠了孤里。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡橘洞,死狀恐怖捌袜,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情炸枣,我是刑警寧澤琢蛤,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站抛虏,受9級特大地震影響博其,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜迂猴,卻給世界環(huán)境...
    茶點故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一慕淡、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧沸毁,春花似錦峰髓、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至搂誉,卻和暖如春徐紧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背炭懊。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工并级, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人侮腹。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓嘲碧,卻偏偏與公主長得像,于是被迫代替她去往敵國和親父阻。 傳聞我的和親對象是個殘疾皇子愈涩,可洞房花燭夜當晚...
    茶點故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內(nèi)容