找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 2732|回復(fù): 0
打印 上一主題 下一主題
收起左側(cè)

Android中“不要臉”的Service

[復(fù)制鏈接]
跳轉(zhuǎn)到指定樓層
樓主
ID:90014 發(fā)表于 2015-9-14 13:01 | 只看該作者 回帖獎勵 |倒序?yàn)g覽 |閱讀模式
     Service作為Android中的四大組件之一,經(jīng)常用他處理一些持續(xù)性的、不需要UI的事件。現(xiàn)如今大多數(shù)程序都會有一個或多個不要臉的Service,所謂不要臉就是你剛剛強(qiáng)制關(guān)閉他,沒幾秒他又屁顛屁顛的自己活過來了。。。對于這種Kill不掉的Service讓人惱怒。因?yàn)樗仲M(fèi)電又費(fèi)流量。但是他也有自己的好處、確保一些時時提醒或是其他的功能。

    制作一個簡單的“不要臉”的Service有兩種思路。其實(shí)都差不多的了。。。(參照的是CSDN大神以及其他人的源

    1、利用系統(tǒng)廣播(如開機(jī)、屏幕喚醒)觸發(fā)自己的Server或其他你想干的事情。
    2、利用定時任務(wù)每隔短時間觸發(fā)啟動事件

    先說第一種:
    首先要創(chuàng)建一個廣播監(jiān)聽(繼承BroadcastReceiver基類),在onReceive方法中啟動(我以Server為例)
       @Overridepublic void onReceive(Context context, Intent intent)
{
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
Intent startServiceIntent = new Intent(context, MyService.class);
startServiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(startServiceIntent);
}
}
         當(dāng)然也可以判斷接收到的廣播類型并作出相應(yīng)的相應(yīng),如下:
                if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
System.out.println("手機(jī)開機(jī)了...bootComplete!");
} else if (Intent.ACTION_PACKAGE_ADDED.equals(arg1.getAction())) {
System.out.println("新安裝了應(yīng)用程序....pakageAdded!");
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(arg1.getAction())) {
System.out.println("應(yīng)用程序被卸載了....pakageRemoved!");
} else if (Intent.ACTION_USER_PRESENT.equals(arg1.getAction())) {
System.out.println("手機(jī)被喚醒了.....userPresent");
}
     其次在清單文件(AndroidManifest.xml)中注冊廣播
        <receiver android:>
            <intent-filter>
                <action android: />
                <category android: />
            </intent-filter>
        </receiver>

    然后說第二種 :定時啟動服務(wù),這個需要用到
AlarmManager與PendingIntent,這兩個定時任務(wù)類。即使是當(dāng)前Activity被殺死了也是可以執(zhí)行的。
    當(dāng)Server第一次啟動的時候會觸發(fā)onCreate,故在此方法中寫定時觸發(fā)Server就可以了
        
AlarmManager mAlarmManager = null;
        PendingIntent mPendingIntent = null;


@Override
public void onCreate()
{
//start the service through alarm repeatly
        Intent intent = new Intent(getApplicationContext(), MyService.class);        
mAlarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
mPendingIntent = PendingIntent.getService(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
long now = System.currentTimeMillis();
                // 60S后啟動Intent

mAlarmManager.setInexactRepeating(AlarmManager.RTC, now, 6000, mPendingIntent);

super.onCreate();
}




分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 分享淘帖 頂 踩
回復(fù)

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

手機(jī)版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機(jī)教程網(wǎng)

快速回復(fù) 返回頂部 返回列表