|
2應(yīng)用的目標(biāo)很簡(jiǎn)單,用戶設(shè)定一個(gè)時(shí)間,到時(shí)后停止音樂的播放。所以我們需要使用Service來(lái)保持在Activity結(jié)束后繼續(xù)維持計(jì)時(shí)。當(dāng)用戶設(shè)定某一時(shí)間后啟動(dòng)一個(gè)Service,之后所有操作由Service驅(qū)動(dòng),Activity界面就可以關(guān)閉了,在Service中我們要使用 AlarmService來(lái)實(shí)現(xiàn)計(jì)時(shí),當(dāng)時(shí)間到時(shí)AlarmManager會(huì)發(fā)送一個(gè)廣播,你需要一個(gè)BroadcastReceiver來(lái)處理這個(gè)廣播完成時(shí)間到時(shí)時(shí)要完成的操作。
如果說正在看這篇文章的你還不知道什么是Service或BroadcastReceiver的話,您需要自己另找資料學(xué)習(xí)一下了,我只能簡(jiǎn)單說 Service是一個(gè)后臺(tái)的應(yīng)用程序,它沒有顯示的界面所以也就不能與用戶交互,但是它還是能夠通信的。Service有兩種啟動(dòng)的方式一個(gè)使用 Context.startService()啟動(dòng),另一個(gè)則是使用Context.bindService()來(lái)啟動(dòng),兩者存在這區(qū)別。而 BroadCastReceiver就是一個(gè)收音機(jī),這個(gè)BroadCastReceiver會(huì)響應(yīng)一個(gè)有特定標(biāo)識(shí)的消息。我也只能簡(jiǎn)單的說這一點(diǎn),更多的內(nèi)容你可以自己在Google上搜索一些關(guān)于Service和BroadcastReceiver的資料吧。
首先是要做的是一個(gè)Service,你需要繼承Service類并實(shí)現(xiàn)它的onCreate(),onStart(),onDestroy(),onBind()方法,其中onBind()方法是必須實(shí)現(xiàn)的。
實(shí)例代碼如下
package com.shinestudio.sleepMusic.service;
import java.util.Calendar;
//......
import com.shinestudio.sleepMusic.AlarmReceiver;
import com.shinestudio.sleepMusic.StartActivity;
public class SleepMusicService extends Service {
private static String TAG = "sleepMusicService";
private static SleepMusicService sms = null;
private static int NOTIFICATION_ID = 0x1209;
private String settingTime;
public static Service getService() {
return sms;
}
/*
這里有個(gè)小方法有必要說一下,在Service或Activity中我們可以寫一個(gè)靜態(tài)的方法來(lái)保留自己的實(shí)體。這樣在其他的地方就可以獲取到了。
private static SleepMusicService sms = null; 用來(lái)存儲(chǔ)自己的實(shí)體
在onCreate()中 使用sms = this;來(lái)存儲(chǔ)實(shí)體
編寫一個(gè)靜態(tài)的getService()來(lái)返回實(shí)體就行了。
*/
@Override
public void onCreate() {
super.onCreate();
sms = this;
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(TAG, "Service onStart");
//獲取AlarmManager
AlarmManager am = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
//獲取當(dāng)前的時(shí)間
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
// 只對(duì)秒 做修改
// c.set(Calendar.HOUR_OF_DAY, hourOfDay);
// c.set(Calendar.MINUTE, c.get(Calendar.MINUTE));
c.set(Calendar.SECOND, c.get(Calendar.SECOND) + 5); //定時(shí)5秒
//c.set(Calendar.MILLISECOND, 0);
//設(shè)置消息的響應(yīng)
Intent ii = new Intent(this, AlarmReceiver.class);
PendingIntent pii = PendingIntent.getBroadcast(this, 0, ii, 0);
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pii);
//使用Toast提示用戶
Toast.makeText(this, "AlarmSet Finish", Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
AlarmManager am = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
Intent i = new Intent(this, StartActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
am.cancel(pi);
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
完成了Service,之后就是寫一個(gè)Activity來(lái)啟動(dòng)這個(gè)Service,其中為了保證在應(yīng)用退出后Servcie繼續(xù)運(yùn)行,所以要使用startService()來(lái)啟動(dòng)Service。一般關(guān)于Service的資料上都是有的。
package com.shinestudio.sleepMusic;
import java.util.Iterator;
import java.util.List;
//......
import com.shinestudio.sleepMusic.service.ISleepMusicService;
import com.shinestudio.sleepMusic.service.SleepMusicService;
import com.shinestudio.sleepMusic.unit.TimerPickerUIStruct;
public class StartActivity extends Activity {
private static String TAG = "sleepMusic - StartActivity";
private ListView timerlist;
private TimerPicker timerPicker;
private TimerPickerUIStruct tpui;
private Button startButton;
private Button cancelButton;
private Button restartButton;
//當(dāng)點(diǎn)擊開始按鈕
private OnClickListener startButtonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent isleepMusicService = new Intent(StartActivity.this,
SleepMusicService.class);
/*
在Service啟動(dòng)之前可以使用Intent來(lái)傳遞參數(shù)給Service ,方法如下
目前的代碼只是演示,與功能無(wú)關(guān)
*/
Bundle setting = new Bundle();
setting.putString(“TIME_SETTING”, "5s");
// 在Service中使用“TIME_SETTING”這個(gè)標(biāo)簽就可以從Intent取出5s 這個(gè)字符串了
isleepMusicService.putExtras(setting);
startService(isleepMusicService);
}
};
//點(diǎn)擊取消按鈕
private OnClickListener cancelButtonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent sleepMusicService = new Intent(StartActivity.this,
SleepMusicService.class);
//停止服務(wù)
stopService(sleepMusicService);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ...... 代碼省略
// 獲取Layout中的按鈕
startButton = (Button) findViewById(R.id.b_start);
cancelButton = (Button) findViewById(R.id.b_cancel);
startButton.setOnClickListener(startButtonClickListener);
cancelButton.setOnClickListener(cancelButtonClickListener);
restartButton = (Button) findViewById(R.id.b_restart);
restartButton.setOnClickListener(restartButtonClickListener);
}
}
完成了這個(gè)Activity之后,就容易的多了,剩下的就是BroadcastReceiver了,新建一個(gè)類繼承BroadcastReceiver
并且實(shí)現(xiàn)onReceive()方法
package com.shinestudio.sleepMusic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "時(shí)間到", Toast.LENGTH_SHORT).show();
}
}
當(dāng)Service中的AlarmManager完成計(jì)時(shí)后將廣播消息給AlarmReceiver,這樣就會(huì)顯示Toast給用戶了。
在AndroidManifest.xml中添加activity、service、和receiver的設(shè)置
< ?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.shinestudio.sleepMusic" android:versionCode="1"
android:versionName="1.0">
< application android:icon="@drawable/icon" android:label="@string/app_name">
< activity android:name=".StartActivity" android:label="@string/app_name"
android:theme="@android:style/Theme.Black.NoTitleBar">
< intent-filter>
< action android:name="android.intent.action.MAIN" />
< category android:name="android.intent.category.LAUNCHER" />
< /intent-filter>
< /activity>
< service android:name=".service.SleepMusicService">
< /service>
< receiver android:name="AlarmReceiver"></receiver>
< /application>
< /manifest>
附加提供的一點(diǎn)點(diǎn)代碼片
打開HTC HERO 自帶的HTC Music Player
public void openMusicPlayer(){
Open Music Player
Intent musicPlayer = new Intent();
musicPlayer.setAction(Intent.ACTION_MAIN);
musicPlayer.setPackage("com.htc.music");
StartActivity.this.startActivity(musicPlayer);
}
//獲得所有運(yùn)行的service
public static String getRunningServicesInfo(Context context) {
StringBuffer serviceInfo = new StringBuffer();
final ActivityManager activityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> services = activityManager.getRunningServices(100);
Iterator<RunningServiceInfo> l = services.iterator();
while (l.hasNext()) {
RunningServiceInfo si = (RunningServiceInfo) l.next();
serviceInfo.append("pid: ").append(si.pid);
serviceInfo.append("
process: ").append(si.process);
serviceInfo.append("
service: ").append(si.service);
serviceInfo.append("
crashCount: ").append(si.crashCount);
serviceInfo.append("
clientCount: ").append(si.clientCount);
serviceInfo.append("
");
}
return serviceInfo.toString();
}
在看完這堆代碼之后,請(qǐng)您看看這個(gè),這些是Android所提供給用戶的的一下系統(tǒng)的Service
像NotificationManager Vebrator AlarmManager 都是比較常用的。
WINDOW_SERVICE WindowManager 管理打開的窗口程序
LAYOUT_INFLATER_SERVICE LayoutInflater 取得xml里定義的view
ACTIVITY_SERVICE ActivityManager 管理應(yīng)用程序的系統(tǒng)狀態(tài)
POWER_SERVICE PowerManger 電源的服務(wù)
ALARM_SERVICE AlarmManager 鬧鐘的服務(wù)
NOTIFICATION_SERVICE NotificationManager 狀態(tài)欄的服務(wù)
KEYGUARD_SERVICE KeyguardManager 鍵盤鎖的服務(wù)
LOCATION_SERVICE LocationManager 位置的服務(wù),如GPS
SEARCH_SERVICE SearchManager 搜索的服務(wù)
VEBRATOR_SERVICE Vebrator 手機(jī)震動(dòng)的服務(wù)
CONNECTIVITY_SERVICE Connectivity 網(wǎng)絡(luò)連接的服務(wù)
WIFI_SERVICE WifiManager Wi-Fi服務(wù)
TELEPHONY_SERVICE TeleponyManager 電話服務(wù)
|
上一篇: Android 如何使用Alarm下一篇: AlarmManager的使用
|