|
Service作為Android中的四大組件之一,經常用他處理一些持續性的、不需要UI的事件,F如今大多數程序都會有一個或多個不要臉的Service,所謂不要臉就是你剛剛強制關閉他,沒幾秒他又屁顛屁顛的自己活過來了。。。對于這種Kill不掉的Service讓人惱怒。因為他又費電又費流量。但是他也有自己的好處、確保一些時時提醒或是其他的功能。
制作一個簡單的“不要臉”的Service有兩種思路。其實都差不多的了。。。(參照的是CSDN大神以及其他人的源
1、利用系統廣播(如開機、屏幕喚醒)觸發自己的Server或其他你想干的事情。
2、利用定時任務每隔短時間觸發啟動事件
先說第一種:
首先要創建一個廣播監聽(繼承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);
}
}
當然也可以判斷接收到的廣播類型并作出相應的相應,如下:
if (Intent.ACTION_BOOT_COMPLETED.equals(arg1.getAction())) {
System.out.println("手機開機了...bootComplete!");
} else if (Intent.ACTION_PACKAGE_ADDED.equals(arg1.getAction())) {
System.out.println("新安裝了應用程序....pakageAdded!");
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(arg1.getAction())) {
System.out.println("應用程序被卸載了....pakageRemoved!");
} else if (Intent.ACTION_USER_PRESENT.equals(arg1.getAction())) {
System.out.println("手機被喚醒了.....userPresent");
}
其次在清單文件(AndroidManifest.xml)中注冊廣播
<receiver android:>
<intent-filter>
<action android: />
<category android: />
</intent-filter>
</receiver>
然后說第二種 :定時啟動服務,這個需要用到AlarmManager與PendingIntent,這兩個定時任務類。即使是當前Activity被殺死了也是可以執行的。
當Server第一次啟動的時候會觸發onCreate,故在此方法中寫定時觸發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();
}
|
|