這個demo示範了如何利用鬧鐘定時器啟動一個服務,用法與上一個demo基本類似,隻是啟動的是服務而上個demo 發送是的廣播。
* 這裡需要注意的是:在本例中每隔20秒啟動一次服務,而服務在啟動後,向系統通知欄中發送了一個通知消息 而後單獨開啟一個線程去執行服務中需要進行的複雜操作,操作完成後結束服務。
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/info" />
<Button
android:id="@+id/start_service_schedule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Alarm Service"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"/>
<Button
android:id="@+id/stop_service_schedule"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Alarm Service"
android:layout_gravity="center_horizontal"
android:layout_marginTop="5dp"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends Activity {
private PendingIntent senderService;
private AlarmManager am;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(MainActivity.this, AlarmService.class);
senderService = PendingIntent.getService(MainActivity.this, , intent,
);
setContentView(R.layout.activity_main);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
Button bt_start = (Button) findViewById(R.id.start_service_schedule);
Button bt_stop = (Button) findViewById(R.id.stop_service_schedule);
bt_start.setOnClickListener(startServiceListener);
bt_stop.setOnClickListener(stopServiceListener);
}
private OnClickListener startServiceListener = new OnClickListener() {
@Override
public void onClick(View v) {
long firstTime = SystemClock.elapsedRealtime();
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,
* , senderService);
Toast.makeText(MainActivity.this, "定時啟動服務任務已經開啟!", ).show();
}
};
private OnClickListener stopServiceListener = new OnClickListener() {
@Override
public void onClick(View v) {
am.cancel(senderService);
Toast.makeText(MainActivity.this, "定時啟動服務任務已經停止!", ).show();
}
};
}
AlarmService.java
public class AlarmService extends Service {
private static final int NOTIFICATION_ID = ;
private NotificationManager nm;
@Override
public void onCreate() {
super.onCreate();
// 擷取系統通知管理器
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 向系統通知欄發送通知消息,并在通知欄中顯示消息
showNotification();
// AlarmService表示為線程的名稱
Thread thr = new Thread(null, mTask, "AlarmService");
thr.start();
}
private Runnable mTask=new Runnable() {
@Override
public void run() {
long endTime=System.currentTimeMillis()+*;
while(System.currentTimeMillis()<endTime){
//加一把同步鎖
synchronized (mBinder) {
try {
mBinder.wait(endTime-System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//結束服務
AlarmService.this.stopSelf();
}
};
//定義一個IBinder接口的執行個體
private IBinder mBinder=new Binder(){
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
// TODO Auto-generated method stub
return super.onTransact(code, data, reply, flags);
}
};
@SuppressWarnings("deprecation")
private void showNotification() {
String text = "服務正在運作...";
String label = "鬧鐘定時服務示例!";
// 定義一個延遲意圖,當我們點選這條通知消息時,再次啟動我們的主程式
PendingIntent contentIntent = PendingIntent.getActivity(this, ,
new Intent(this, MainActivity.class), );
// 定義一個notification
Notification.Builder builder = new Builder(this);
builder.setSmallIcon(R.drawable.stat_sample);
builder.setContentText(text);
builder.setWhen(System.currentTimeMillis());
builder.setContentTitle(label);
builder.setContentIntent(contentIntent);
builder.setTicker(text);
Notification notification = builder.build();
//Notification notification=new Notification(R.drawable.stat_sample, text, System.currentTimeMillis());
// 設定在系統通知欄中顯示的通知消息的界面資訊
//notification.setLatestEventInfo(this, label, text, contentIntent);
//發送消息通知
nm.notify(NOTIFICATION_ID, notification);
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onDestroy() {
super.onDestroy();
//根據notification的Id取消對應的系統通知
nm.cancel(NOTIFICATION_ID);
Toast.makeText(this, "服務結束!", ).show();
}
}
最後别忘了在配置檔案中對服務進行配置