android组件启动,Android四大组件Service之StartService启动
對(duì)于Service兩種方式在概述里已經(jīng)介紹了,下面是學(xué)習(xí)是StartService的代碼實(shí)例。
service啟動(dòng)代碼:
package com.example.service01;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class Service01 extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null; // 由于不是綁定模式,所以在啟動(dòng)Service時(shí)不會(huì)被調(diào)用,直接返回null即可
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
System.out.println("Example Service --> ONCreate");
super.onCreate();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
System.out.println("Example Service --> ONDestory");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
System.out.println("Example Service --> OnStartCommand");
return super.onStartCommand(intent, flags, startId);
}
}
Activity代碼:
package com.example.service01;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button buttonStart =null;
private Button buttonStop =null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = (Button)findViewById(R.id.buttonstart);
buttonStop = (Button)findViewById(R.id.buttonstop);
buttonStart.setOnClickListener(Listener);
buttonStop.setOnClickListener(Listener);
// buttonStart.setOnClickListener(new buttonStartOnClickLister());
//buttonStop.setOnClickListener(new buttonStopOnClickLister());
}
private OnClickListener Listener = new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,Service01.class); //必須放到類中聲明
switch (arg0.getId()) {
case R.id.buttonstart:
startService(intent); // 調(diào)用StartService啟動(dòng)服務(wù)
break;
case R.id.buttonstop:
stopService(intent); // 調(diào)用stopService 關(guān)閉服務(wù)
default:
break;
}
}
};
/*
class buttonStartOnClickLister implements OnClickListener{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
class buttonStopOnClickLister implements OnClickListener
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
*/
}
AndroidManifest.xml中:
總結(jié)
以上是生活随笔為你收集整理的android组件启动,Android四大组件Service之StartService启动的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 日本大正年间有珍珠吗?
- 下一篇: Android短消息备份闪退,Andro