Android 开发笔记—— Service

         Service是Andorid系统提供的四大组件之一,它的地位和Activity是并列的,只是使用的频率没有Activity高。Service就是运行于后台的一种服务程序,一般很少和用户交互,因此没有可视化界面。
         定义一个Service类只要继承Service类即可,实现其生命周期中的方法就可以了,另外,一个定义好的Service组件必须要在AndoridManifest.xml文件中注册才能够使用。

         Service有自己的生命周期,可以调用startService()启动一个Service或者使用bindService()来绑定一个service,还可以通过RPC(远程进程调用)机制来实现不同进程间Service的调用。       
        Service中定义了一系列和自身生命周期相关的方法:

onBind(Intent intent):是必须实现的一个方法,返回一个绑定的接口给Service。

onCreate():当Service第一次被创建时,由系统调用。

onStart(Intent intent,int startId):当通过startService()方法启动Service时,该方法被调用。

onDestroy():当Service不再使用,系统调用该方法

请看下面例子:

MyService(这里定义了一个Service,它继承自Service,并重写了当中的一些方法)

public class MyService extends Service {
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		Log.i("SERVICE", "onBind.................");
		Toast.makeText(MyService.this, "onBind.................", Toast.LENGTH_LONG).show();
		return null;
	}

	public void onCreate()
	{
		Log.i("SERVICE", "onCreate................");
		Toast.makeText(MyService.this, "onCreate................", Toast.LENGTH_LONG).show();
	}
	public void onStart(Intent intent,int startId)
	{
		Log.i("SERVICE", "onStart.................");
		Toast.makeText(MyService.this, "onStart.................", Toast.LENGTH_LONG).show();
	}
	public void onDestroy()
	{
		Log.i("SERVICE", "onDestroy.................");
		Toast.makeText(MyService.this, "onDestroy.................", Toast.LENGTH_LONG).show();
	}
}


 

在AndroidManifest.xml文件中注册Service如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="MyFristService" android:icon="@drawable/icon">
        <activity android:name="MyActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name="MyService">
			<intent-filter>
				<action android:name="com.example.MYSERVICE"/>
			</intent-filter>
		</service>
    </application>
</manifest> 

 

在Activity内,调用此Service:

public class MyActivity extends Activity {
    private Button btnStart;
    private Button btnStop;
    private Button btnBind;
    private Button btnUnbind;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnBind = (Button) findViewById(R.id.bindButton);
        btnStart = (Button) findViewById(R.id.startButton);
        btnStop = (Button) findViewById(R.id.stopButton);
        btnUnbind = (Button) findViewById(R.id.unbindButton);

        btnStart.setOnClickListener(startListener);
        btnStop.setOnClickListener(stopListener);
        btnBind.setOnClickListener(bindListener);
        btnUnbind.setOnClickListener(unbindListener);
    }
    private View.OnClickListener startListener=new View.OnClickListener()
    {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent=new Intent();
			intent.setAction("com.example.MYSERVICE");
			startService(intent);
		}
    };
    private View.OnClickListener stopListener=new View.OnClickListener()
    {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent=new Intent();
			intent.setAction("com.example.MYSERVICE");
			stopService(intent);
		}
    };
    private ServiceConnection conn=new ServiceConnection()
    {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			Log.i("SERVICE", "connection success");
			Toast.makeText(MyActivity.this, "connection success", Toast.LENGTH_LONG).show();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			Log.i("SERVICE", "connection success");
			Toast.makeText(MyActivity.this, "connection failure", Toast.LENGTH_LONG).show();
		}
    };
    private View.OnClickListener bindListener=new View.OnClickListener()
    {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent=new Intent();
			intent.setAction("com.example.MYSERVICE");
			bindService(intent,conn, Service.BIND_AUTO_CREATE);
		}
    };
    private View.OnClickListener unbindListener=new View.OnClickListener()
    {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent=new Intent();
			intent.setAction("com.example.MYSERVICE");
			unbindService(conn);
		}
    };
}


 

源码:下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值