服務使程序實現後臺運行,服務一般包含線程,線程依賴於應用進程,同理服務也是依賴
每一個創建該服務的應用進程,每一個打開的應用程序可以成爲一個進程。
可成爲一個進程,服務並不會自動開啓線程,所有的代碼都是默認在主線程裏面運行的,
所以一般是在服務裏面創建子線程,否則就可能出現主線程被阻塞的情況。
Android線程:
如果想進行UI操作,在子線程裏是不能實現的,必須到主線程才能實現,一般在子線程
進行hanlder.sendMessage(message)—–然後在handler裏進行邏輯操作
private Handler handler = new Handler(){
public void handleMessage(Message msg){
//邏輯操作
}
};
線程信息的處理機制圖:
Sevice(服務):
服務的生命週期:onBind(),onCreate(),onStartCommand(),onDestroy()
public class MyService extends Service {
private DownLoadBinder mBinder = new DownLoadBinder();
//實現活動和服務的通信或者使聯繫更緊密
//創建一個實例,然後再onBind()裏面返回一個實例,然後再MainActivity中
//新建ServiceConnection對象,在這對象裏面重寫兩個方法,實現對mBlid
//實例的調用
class DownLoadBinder extends Binder{
public void startDownload(){
Log.d("MyService", "startDownload");
}
public int getProgress(){
Log.d("MyService", "getProgress");
return 0;
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
@Override
public void onCreate(){
super.onCreate();
//前臺服務用法
Notification notification = new Notification(R.drawable.ic_launcher, "Notification",
System.currentTimeMillis());
Intent notificationItent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationItent,0 );
notification.setLatestEventInfo(this, "This is Title", "This is content",pendingIntent );
//設置到通知欄顯示一個前臺服務
//這個時候的前臺服務和通知有個很大的區別
//即服務不能一拉消除而通知可以
startForeground(1, notification);
Log.d("MyService", "onCreate executed");
}
@Override
public int onStartCommand(Intent intent,int flags,int startId){
Log.d("MyService", "onStartCommand executed");
return super.onStartCommand(intent, flags, startId);
//邏輯操作,在這裏一般創建子線程
}
@Override
public void onDestroy(){
super.onDestroy();
Log.d("MyService", "onDestroy executed");
}
}
public class MainActivity extends Activity implements OnClickListener{
private Button startService;
private Button stopService;
private Button startIntentService;
//實現活動和服務的聯繫即是綁定服務
private Button blind;
private Button Unblind;
//由於定義了一個內部類,所以要調用內部類的對象則
private MyService.DownLoadBinder downLoadBinder;
//然後還要通過一個ServiceConnection 實現對兩個方法的調用
//serviceConnection,在綁定和解綁服務傳入
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
// Log.d("MyService", "unblinder OK");
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
downLoadBinder = (MyService.DownLoadBinder)service;
downLoadBinder.startDownload();
downLoadBinder.getProgress();
}
};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
startIntentService = (Button)findViewById(R.id.intent_service_button);
startService = (Button)findViewById(R.id.start_service_button);
stopService = (Button)findViewById(R.id.stop_service_button);
blind = (Button)findViewById(R.id.bind_service_button);
Unblind = (Button)findViewById(R.id.ubind_service_button);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
blind.setOnClickListener(this);
Unblind.setOnClickListener(this);
startIntentService.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.start_service_button:
Intent startIntent = new Intent(this,MyService.class);
//開啓服務
startService(startIntent);
Toast.makeText(this, "開啓服務", Toast.LENGTH_SHORT).show();
break;
case R.id.stop_service_button:
Intent stopIntent = new Intent(this,MyService.class);
stopService(stopIntent);
Toast.makeText(this, "關閉服務", Toast.LENGTH_SHORT).show();
break;
case R.id.bind_service_button:
Intent bindIntent = new Intent(this,MyService.class);
bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
//綁定服務
break;
case R.id.ubind_service_button:
//解綁服務
unbindService(serviceConnection);
break;
case R.id.intent_service_button:
Log.d("MainActivity", "Thread id is "+Thread.currentThread().getId());
Intent intentService = new Intent(this,MyIntentService.class);
startService(intentService);
break;
default:
break;
}
}
}
標準服務案例:
定時啓動服務,實現定時操作
//AlarmManager對象
LongService extends Service{
onStartCommand(){
new Thread(new Runnable(){
@Override
public void run(){
}
}).start();
}
}
//這裏是實現的是定時執行任務,只要把任務
Log.d("LongRunningService", "executed at "+new Date().toString());替換就可以
public class LongRunningService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
//執行任務
Log.d("LongRunningService", "executed at "+new Date().toString());
}
}).start();
//AlarmManager 對象
AlarmManager manager = (AlarmManager)getSystemService(ALARM_SERVICE);
int laytime = 6*1000;
long triggerAtTime = SystemClock.elapsedRealtime()+laytime;
Intent i = new Intent(this,AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
//定時時間從系統開機開始,喚醒CPU
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime , pi);
//在這裏的執行到廣播接收器裏面開啓了新的服務,然後在廣播接收器和LongRunningService不斷循環不斷執行任務
return super.onStartCommand(intent, flags, startId);
}
}
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent i = new Intent(context,LongRunningService.class);
context.startService(i);
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent i = new Intent(this,LongRunningService.class);
startService(i);
}
}
//別忘了在
<application>
<service android:name=".LongRunningService"></service>
<receiver android:name=".AlarmReceiver"></receiver>
</application>
分析: 首先從MainActivity開始啓動
Intent i = new Intent(this,LongRunningService.class);
startService(i);
在LongRunningService.class啓動了AlarmReceiver
在AlarmReceiver中又啓動了LongRunningService.class
這樣不斷循壞開始