定時AlarmManager迴圈執行後臺任務和多個定時迴圈後臺任務寫在一起
阿新 • • 發佈:2018-12-23
定時迴圈執行某些任務,在開發中是很常見的一種方式,Android中有兩種定時器可以實現,一種是Alarm,另一種是AlarmManager,Alarm在Android4.4以後,這種方式的定時器不太準確,Android官方為了優化手機電池使用時間,將多個差不多時間差的Alarm定時器放在一起執行,導致部分計時器先執行或者或執行。相比於Alarm,AlarmManager是準確執行的。所以這裡我們不考慮Alarm定時器,以AlarmManager作為示例。
1. 建立一個定時迴圈任務(定時迴圈後臺任務建立挺簡單的,主要是多個定時迴圈會有些麻煩),按照慣例,先直接上程式碼。
- 首先建立一個介面TimeTask.java,直觀地顯示出後臺的執行資訊。
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.mrc.csdndemo.R;
public class TimeTask extends AppCompatActivity implements View.OnClickListener {
Button mOpenBtn ,mCloseBtn ,mOpenMoreBtn ,mCloseMoreBtn;
Intent mOneIntent = null ;
Intent mMoreIntent =null;
TimeTaskService timeTaskService ;
SharedPreferences sharedPreferences ;
SharedPreferences.Editor editor ;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_time_task);
/*sharedPreferences =getApplicationContext().getSharedPreferences("com.example.mrc.csdnDemo" , 0);
editor=sharedPreferences.edit();
editor.putInt("count",0);
editor.commit();*/
findView();
Init();
}
void findView(){
mOpenBtn = (Button)findViewById(R.id.open_time_task);
mCloseBtn = (Button)findViewById(R.id.close_time_task);
mOpenMoreBtn = (Button)findViewById(R.id.open_more_time_task);
mCloseMoreBtn = (Button)findViewById(R.id.close_more_time_task);
mOpenBtn.setOnClickListener(this);
mCloseBtn.setOnClickListener(this);
mOpenMoreBtn.setOnClickListener(this);
mCloseMoreBtn.setOnClickListener(this);
}
void Init(){
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.open_time_task :
mOneIntent =new Intent(this ,TimeTaskService.class) ;
/*mOneIntent.setAction("ITOP.MOBILE.SIMPLE.SERVICE.SENSORSERVICE");*/
startService(mOneIntent);
break;
case R.id.close_time_task :
Intent intentOneStop = new Intent(this, TimeTaskService.class);
/*Intent intent =new Intent();*/
/* intent.setAction("ITOP.MOBILE.SIMPLE.SERVICE.SENSORSERVICE");*/ //android5.0以下才適合使用
stopService(intentOneStop);
break;
case R.id.open_more_time_task :
mMoreIntent =new Intent(this ,MoreTimeTaskService.class) ;
/*mOneIntent.setAction("ITOP.MOBILE.SIMPLE.SERVICE.SENSORSERVICE");*/
startService(mMoreIntent);
break;
case R.id.close_more_time_task :
Intent intentMoreStop = new Intent(this, MoreTimeTaskService.class);
/*Intent intentMoreStop =new Intent();*/
/* intent.setAction("ITOP.MOBILE.SIMPLE.SERVICE.SENSORSERVICE");*/ //android5.0以下才適合使用
stopService(intentMoreStop);
break;
default:break;
}
}
}
- 相對應的activity_time_task.xml佈局
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.mrc.csdndemo.BackgroundTimeTask.TimeTask">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center">
<Button
android:id="@+id/open_time_task"
android:layout_gravity="center_horizontal"
android:layout_width="240dp"
android:layout_height="48dp"
android:text="開啟一個定時任務"
android:background="@drawable/button_style"
android:textSize="17sp"
android:textColor="@color/text_white"
android:layout_marginTop="16dp"/>
<Button
android:id="@+id/close_time_task"
android:layout_gravity="center_horizontal"
android:layout_width="240dp"
android:layout_height="48dp"
android:text="關閉一個定時任務"
android:background="@drawable/button_style"
android:textSize="17sp"
android:textColor="@color/text_white"
android:layout_marginTop="16dp"/>
<Button
android:id="@+id/open_more_time_task"
android:layout_gravity="center_horizontal"
android:layout_width="240dp"
android:layout_height="48dp"
android:text="開啟多個定時任務"
android:background="@drawable/button_style"
android:textSize="17sp"
android:textColor="@color/text_white"
android:layout_marginTop="16dp"/>
<Button
android:id="@+id/close_more_time_task"
android:layout_gravity="center_horizontal"
android:layout_width="240dp"
android:layout_height="48dp"
android:text="關閉多個定時任務"
android:background="@drawable/button_style"
android:textSize="17sp"
android:textColor="@color/text_white"
android:layout_marginTop="16dp"/>
</LinearLayout>
</ScrollView>
介面效果如下:
- 以上都不用解釋,相信都能看懂,接下來建立後臺服務的事情
建立一個後臺服務:TimeTaskService.java ,這個服務在沒有特殊情況下是不會關閉的
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.util.Calendar;
public class TimeTaskService extends Service {
private static final int INTERVAL_TIME = 10 ;
AlarmManager alarmManager ;
PendingIntent pIntent ;
SharedPreferences sharedPreferences ;
SharedPreferences.Editor editor ;
Calendar mCalendar ;
public TimeTaskService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
sharedPreferences =getApplicationContext().getSharedPreferences("com.example.mrc.csdnDemo" , 0);
sharedPreferences.edit();
//這裡模擬後臺操作
Handler handler=new Handler(Looper.getMainLooper());
handler.post(new Runnable(){
public void run(){
int count =sharedPreferences.getInt("count" ,0);
count ++ ;
Log.e("messages","迴圈執行了"+ count +"次定時任務,執行時間為:"+ System.currentTimeMillis());
Toast.makeText(getApplicationContext() ,"迴圈執行了"+ count +"次定時任務,執行時間為:"+ System.currentTimeMillis() ,Toast.LENGTH_LONG).show();
editor = sharedPreferences.edit();
editor.putInt("count" ,count);
editor.commit();
}
});
mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(System.currentTimeMillis());
mCalendar.add(Calendar.SECOND, INTERVAL_TIME);
//通過AlarmManager定時啟動廣播
alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
Intent timeTaskIntent=new Intent(this, AlarmReceiver.class);
pIntent=PendingIntent.getBroadcast(this,0,timeTaskIntent ,PendingIntent.FLAG_CANCEL_CURRENT);
int apiLevel = getApiLevel();
if (apiLevel < Build.VERSION_CODES.KITKAT) {
Log.d("api<19", "setExactAlarmCompat ");
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), INTERVAL_TIME, pIntent);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntent);
}
Log.d("19<api<23", "setExactAlarmCompat ");
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntent);
Log.d("api>23", "setExactAlarmCompat ");
}
return super.onStartCommand(intent, flags, startId);
}
public static int getApiLevel() {
try {
Field f = Build.VERSION.class.getField("SDK_INT");
f.setAccessible(true);
return f.getInt(null);
} catch (Throwable e) {
return 3;
}
}
@Override
public void onDestroy(){
alarmManager.cancel(pIntent);
Handler handler=new Handler(Looper.getMainLooper());
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext() ,"停止後臺迴圈任務,停止執行時間為:"
+ System.currentTimeMillis() , Toast.LENGTH_LONG ).show();
}
});
Log.e("messages","停止後臺迴圈任務,停止執行時間為:"+ System.currentTimeMillis());
}
}
這是建立一個定時後臺服務的主要程式碼:
mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(System.currentTimeMillis());
mCalendar.add(Calendar.SECOND, INTERVAL_TIME);
//通過AlarmManager定時啟動廣播
alarmManager= (AlarmManager) getSystemService(ALARM_SERVICE);
Intent timeTaskIntent=new Intent(this, AlarmReceiver.class);
pIntent=PendingIntent.getBroadcast(this,0,timeTaskIntent ,PendingIntent.FLAG_CANCEL_CURRENT);
int apiLevel = getApiLevel();
if (apiLevel < Build.VERSION_CODES.KITKAT) {
Log.d("api<19", "setExactAlarmCompat ");
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), INTERVAL_TIME, pIntent);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntent);
}
Log.d("19<api<23", "setExactAlarmCompat ");
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntent);
Log.d("api>23", "setExactAlarmCompat ");
}
AlarmManager是一個定時器,在不同的Android版本里AlarmManager的執行方法也不同,具體看程式碼。 PendingIntent是一個即將執行的意圖,和Intent的最主要的區別是PendingIntent是即將執行的,Intent是立即執行的,怎麼解釋呢,就是PendingIntent是等待某些訊號才執行一般配合AlarmManager或者Alarm等一起使用。PendingIntent的使用方法和Intent也有很大差異。在PendingIntent裡還嵌入一個Intent,這才是真正的意圖。
- 執行TimeTaskService服務後,會跳轉到一個廣播類,廣播類會定時回撥TimeTaskService服務,這樣就做到定時迴圈執行的效果。其實挺簡單的。下面是AlarmReceiver.java廣播類的程式碼:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class AlarmReceiver extends BroadcastReceiver {
SharedPreferences sharedPreferences ;
SharedPreferences.Editor editor ;
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, TimeTaskService.class);
context.startService(i);
}
}
仔細看程式碼,感覺也不是很難,這種定時後臺任務其實很常用,學一學沒什麼弊端。
2.定時迴圈執行多個任務(這裡指的是在一個後臺服務裡執行定時間隔都不一樣的任務,這要解決如何知道執行了哪一個定時任務,又不影響其他定時任務的問題,當然,建立多個服務和廣播類也可以實現,但是博主比較死心眼,就想在一個服務Service裡把所有需求實現。後來通過不斷摸索,最終實現了),按照慣例,先獻上程式碼:
- 介面的實現和上面一致,這裡就不多說了,直接說後臺服務。建立MoreTimeTaskService.java服務,程式碼如下:
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.util.Calendar;
public class MoreTimeTaskService extends Service {
private static final int INTERVAL_TIME_ONE = 10 ;
private static final int INTERVAL_TIME_TWO = 15 ;
private static final int INTERVAL_TIME_THREE = 20 ;
AlarmManager mAlarmManagerOne;
AlarmManager mAlarmManagerTwo;
AlarmManager mAlarmManagerThree;
PendingIntent pIntentOne ;
PendingIntent pIntentTwo ;
PendingIntent pIntentThree ;
SharedPreferences sharedPreferences ;
SharedPreferences.Editor editor ;
Calendar mCalendar ;
public MoreTimeTaskService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
sharedPreferences =getApplicationContext().getSharedPreferences("com.example.mrc.csdnDemo" , 0);
sharedPreferences.edit();
int type = sharedPreferences.getInt("type" ,0);
//1表示執行第一個定時任務 2,3同理 ;0表示未執行,則三個一起執行
mCalendar = Calendar.getInstance();
mCalendar.setTimeInMillis(System.currentTimeMillis());
int apiLevel = getApiLevel();
//這裡模擬後臺操作
if(type ==0){
Handler handlerOne=new Handler(Looper.getMainLooper());
handlerOne.post(new Runnable(){
public void run(){
int countOne =sharedPreferences.getInt("countOne" ,0);
countOne ++ ;
Log.e("messages","第1個定時任務迴圈執行了"+ countOne +"次,執行時間為:"+ System.currentTimeMillis());
Toast.makeText(getApplicationContext() ,"第1個定時任務迴圈執行了"+ countOne +"次,執行時間為:"+ System.currentTimeMillis() ,Toast.LENGTH_LONG).show();
editor = sharedPreferences.edit();
editor.putInt("countOne" ,countOne);
editor.commit();
}
});
Handler handlerTwo=new Handler(Looper.getMainLooper());
handlerTwo.post(new Runnable(){
public void run(){
int countTwo =sharedPreferences.getInt("countTwo" ,0);
countTwo ++ ;
Log.e("messages","第2個定時任務迴圈執行了"+ countTwo +"次,執行時間為:"+ System.currentTimeMillis());
Toast.makeText(getApplicationContext() ,"第2個定時任務迴圈執行了"+ countTwo +"次,執行時間為:"+ System.currentTimeMillis() ,Toast.LENGTH_LONG).show();
editor = sharedPreferences.edit();
editor.putInt("countTwo" ,countTwo);
editor.commit();
}
});
Handler handlerThree=new Handler(Looper.getMainLooper());
handlerThree.post(new Runnable(){
public void run(){
int countThree =sharedPreferences.getInt("countThree" ,0);
countThree ++ ;
Log.e("messages","第3個定時任務迴圈執行了"+ countThree +"次,執行時間為:"+ System.currentTimeMillis());
Toast.makeText(getApplicationContext() ,"第3個定時任務迴圈執行了"+ countThree +"次,執行時間為:"+ System.currentTimeMillis() ,Toast.LENGTH_LONG).show();
editor = sharedPreferences.edit();
editor.putInt("countThree" ,countThree);
editor.commit();
}
});
mCalendar.add(Calendar.SECOND, INTERVAL_TIME_ONE);
//通過AlarmManager定時啟動廣播
mAlarmManagerOne= (AlarmManager) getSystemService(ALARM_SERVICE);
Intent timeTaskIntentOne=new Intent(this, MoreAlarmReceiver.class);
timeTaskIntentOne.putExtra("type" ,1);
pIntentOne=PendingIntent.getBroadcast(this,1,timeTaskIntentOne ,PendingIntent.FLAG_CANCEL_CURRENT);
if (apiLevel < Build.VERSION_CODES.KITKAT) {
Log.d("api<19", "setExactAlarmCompat ");
mAlarmManagerOne.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), INTERVAL_TIME_ONE, pIntentOne);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManagerOne.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentOne);
}
Log.d("19<api<23", "setExactAlarmCompat ");
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManagerOne.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentOne);
Log.d("api>23", "setExactAlarmCompat ");
}
mCalendar.add(Calendar.SECOND, INTERVAL_TIME_TWO);
//通過AlarmManager定時啟動廣播
mAlarmManagerTwo= (AlarmManager) getSystemService(ALARM_SERVICE);
Intent timeTaskIntentTwo=new Intent(this, MoreAlarmReceiver.class);
timeTaskIntentTwo.putExtra("type" ,2) ;
pIntentTwo=PendingIntent.getBroadcast(this,2,timeTaskIntentTwo ,PendingIntent.FLAG_CANCEL_CURRENT);
if (apiLevel < Build.VERSION_CODES.KITKAT) {
Log.d("api<19", "setExactAlarmCompat ");
mAlarmManagerTwo.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), INTERVAL_TIME_TWO, pIntentTwo);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManagerTwo.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentTwo);
}
Log.d("19<api<23", "setExactAlarmCompat ");
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManagerTwo.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentTwo);
Log.d("api>23", "setExactAlarmCompat ");
}
mCalendar.add(Calendar.SECOND, INTERVAL_TIME_THREE);
//通過AlarmManager定時啟動廣播
mAlarmManagerThree= (AlarmManager) getSystemService(ALARM_SERVICE);
Intent timeTaskIntentThree=new Intent(this, MoreAlarmReceiver.class);
timeTaskIntentThree.putExtra("type" ,3) ;
pIntentThree=PendingIntent.getBroadcast(this,3,timeTaskIntentThree ,PendingIntent.FLAG_CANCEL_CURRENT);
if (apiLevel < Build.VERSION_CODES.KITKAT) {
Log.d("api<19", "setExactAlarmCompat ");
mAlarmManagerThree.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), INTERVAL_TIME_THREE, pIntentThree);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManagerThree.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentThree);
}
Log.d("19<api<23", "setExactAlarmCompat ");
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManagerThree.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentThree);
Log.d("api>23", "setExactAlarmCompat ");
}
} else if(type ==1){
Handler handlerOne=new Handler(Looper.getMainLooper());
handlerOne.post(new Runnable(){
public void run(){
int countOne =sharedPreferences.getInt("countOne" ,0);
countOne ++ ;
Log.e("messages","第1個定時任務迴圈執行了"+ countOne +"次,執行時間為:"+ System.currentTimeMillis());
Toast.makeText(getApplicationContext() ,"第1個定時任務迴圈執行了"+ countOne +"次,執行時間為:"+ System.currentTimeMillis() ,Toast.LENGTH_LONG).show();
editor = sharedPreferences.edit();
editor.putInt("countOne" ,countOne);
editor.commit();
}
});
mCalendar.add(Calendar.SECOND, INTERVAL_TIME_ONE);
//通過AlarmManager定時啟動廣播
mAlarmManagerOne= (AlarmManager) getSystemService(ALARM_SERVICE);
Intent timeTaskIntentOne=new Intent(this, MoreAlarmReceiver.class);
timeTaskIntentOne.putExtra("type" ,1);
pIntentOne=PendingIntent.getBroadcast(this,1,timeTaskIntentOne ,PendingIntent.FLAG_CANCEL_CURRENT);
if (apiLevel < Build.VERSION_CODES.KITKAT) {
Log.d("api<19", "setExactAlarmCompat ");
mAlarmManagerOne.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), INTERVAL_TIME_ONE, pIntentOne);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManagerOne.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentOne);
}
Log.d("19<api<23", "setExactAlarmCompat ");
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManagerOne.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentOne);
Log.d("api>23", "setExactAlarmCompat ");
}
}else if(type ==2){
Handler handlerTwo=new Handler(Looper.getMainLooper());
handlerTwo.post(new Runnable(){
public void run(){
int countTwo =sharedPreferences.getInt("countTwo" ,0);
countTwo ++ ;
Log.e("messages","第2個定時任務迴圈執行了"+ countTwo +"次,執行時間為:"+ System.currentTimeMillis());
Toast.makeText(getApplicationContext() ,"第2個定時任務迴圈執行了"+ countTwo +"次,執行時間為:"+ System.currentTimeMillis() ,Toast.LENGTH_LONG).show();
editor = sharedPreferences.edit();
editor.putInt("countTwo" ,countTwo);
editor.commit();
}
});
mCalendar.add(Calendar.SECOND, INTERVAL_TIME_TWO);
//通過AlarmManager定時啟動廣播
mAlarmManagerTwo= (AlarmManager) getSystemService(ALARM_SERVICE);
Intent timeTaskIntentTwo=new Intent(this, MoreAlarmReceiver.class);
timeTaskIntentTwo.putExtra("type" ,2);
pIntentTwo=PendingIntent.getBroadcast(this,2,timeTaskIntentTwo ,PendingIntent.FLAG_CANCEL_CURRENT);
if (apiLevel < Build.VERSION_CODES.KITKAT) {
Log.d("api<19", "setExactAlarmCompat ");
mAlarmManagerTwo.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), INTERVAL_TIME_TWO, pIntentTwo);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManagerTwo.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentTwo);
}
Log.d("19<api<23", "setExactAlarmCompat ");
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManagerTwo.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentTwo);
Log.d("api>23", "setExactAlarmCompat ");
}
}else if(type ==3){
Handler handlerThree=new Handler(Looper.getMainLooper());
handlerThree.post(new Runnable(){
public void run(){
int countThree =sharedPreferences.getInt("countThree" ,0);
countThree ++ ;
Log.e("messages","第3個定時任務迴圈執行了"+ countThree +"次,執行時間為:"+ System.currentTimeMillis());
Toast.makeText(getApplicationContext() ,"第3個定時任務迴圈執行了"+ countThree +"次,執行時間為:"+ System.currentTimeMillis() ,Toast.LENGTH_LONG).show();
editor = sharedPreferences.edit();
editor.putInt("countThree" ,countThree);
editor.commit();
}
});
mCalendar.add(Calendar.SECOND, INTERVAL_TIME_THREE);
//通過AlarmManager定時啟動廣播
mAlarmManagerThree= (AlarmManager) getSystemService(ALARM_SERVICE);
Intent timeTaskIntentThree=new Intent(this, MoreAlarmReceiver.class);
timeTaskIntentThree.putExtra("type" ,3);
pIntentThree=PendingIntent.getBroadcast(this,3,timeTaskIntentThree ,PendingIntent.FLAG_CANCEL_CURRENT);
if (apiLevel < Build.VERSION_CODES.KITKAT) {
Log.d("api<19", "setExactAlarmCompat ");
mAlarmManagerThree.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), INTERVAL_TIME_THREE, pIntentThree);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mAlarmManagerThree.setExact(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentThree);
}
Log.d("19<api<23", "setExactAlarmCompat ");
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAlarmManagerThree.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pIntentThree);
Log.d("api>23", "setExactAlarmCompat ");
}
}
return super.onStartCommand(intent, flags, startId);
}
public static int getApiLevel() {
try {
Field f = Build.VERSION.class.getField("SDK_INT");
f.setAccessible(true);
return f.getInt(null);
} catch (Throwable e) {
return 3;
}
}
@Override
public void onDestroy(){
Handler handler=new Handler(Looper.getMainLooper());
handler.post(new Runnable(){
public void run() {
mAlarmManagerOne.cancel(pIntentOne);
Toast.makeText(getApplicationContext() ,"停止了第1個後臺迴圈任務,停止執行時間為:"
+ System.currentTimeMillis() , Toast.LENGTH_LONG ).show();
mAlarmManagerTwo.cancel(pIntentTwo);
Toast.makeText(getApplicationContext() ,"停止了第2個後臺迴圈任務,停止執行時間為:"
+ System.currentTimeMillis() , Toast.LENGTH_LONG ).show();
mAlarmManagerThree.cancel(pIntentThree);
Toast.makeText(getApplicationContext() ,"停止了第3個後臺迴圈任務,停止執行時間為:"
+ System.currentTimeMillis() , Toast.LENGTH_LONG ).show();