您的位置:首页 > 移动开发 > Android开发

<Android> Service详解 学习(一)

2015-07-17 14:53 525 查看
因为最近想用到Service,所以今天系统的学习了一下Service的用法。

Service给我的感觉就和Activity很相似,都是代表可执行的程序,只不过Service是在后台运行的,没有什么实在的界面。Service一旦启动,和Activity一样,具有生命周期。使用Activity或者Service的判断标准是:如果某个程序组件需要在运行时向用户呈现某种界面,与用户进行交互,就使用Activity,否则就考虑使用Service。

因为与Activity很相似,所以使用方法也差不多,开发service的组件需要开发一个service的子类,然后在AndroidMainfest.xml中配置这个service。

开发一个service的子类,只需要重写提供的几种方法即可。
public class firstService extends Service {

    /*
    必须实现的方法,
    方法返回一个Ibind对象,应用程序可以通过该对象与Service组件通信
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //被关闭之前回调该方法    

    }

    @Override
    public void onCreate() {
        super.onCreate();
        //被创建时回调该方法
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
        //被启动时回调该方法
    }
}


每当service被创建时会调用onCreat()方法,多次启动一个已经被创建的service组件会调用onStartCommand()方法。

在AndroidMainFest.xml中配置该service:
<service android:name=".contentProvider">
            <intent-filter>
                <action android:name="text.service.MyFirstService" />   
            </intent-filter>         
        </service>


无需指定Label,因为是在后台运行,所以意义不大。

当service开发完成后,就可以在程序中运行该service了,运行service有两种方法:

1.通过Context的startService()方法:使用这种方法,访问者与Service之间没有关联,即使访问者退出了,service仍然运行。

1.通过context的bindService()方法,这种方法的区别在于,一旦访问者退出,Service随即终止。

public class MainActivity extends Activity {

    Button start, stop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        start = (Button) findViewById(R.id.button_start);
        stop = (Button) findViewById(R.id.button_stop);

        final Intent intent = new Intent();
        intent.setAction("text.Service.MyFirstService");

        start.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                startService(intent);
            }
        });

        stop.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                stopService(intent);
            }
        });
    }
}
以上只是简单的调用Service

然而,如果service和访问者之间需要进行方法调用或者是数据交换,则应该使用bindService(),unbindservice()方法启动。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: