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

Android Service

2015-09-02 16:41 435 查看
Service是在后台运行,不可交互的一个东西。不能自己运行,需通过activity或者其他Context对象来调用。

两种启动方式:

Context.startService();

Context.bindService();

另外需说明的是,如果在Service的onCreate或者onStart做一些耗时的动作,最好是启动一个新线程来运行这个Service,

因为,在主线程中运行,会影响到程序的UI操作或者阻塞主线程中得其他事情。

创建继承Service子类Myservice,并重写几个方法。

package com.example.smsreciver;

import android.app.Service;

import android.content.Intent;

import android.content.IntentFilter;

import android.os.IBinder;

import android.util.Log;

public class Myservice
extends Service {

@Override

public IBinder onBind(Intent arg0) {

//
TODO Auto-generated method stub

Log.i("",
"onBind");

return
null;

}

@Override  

public
void onCreate() {

//
TODO Auto-generated method stub

Log.i("",
"onCreate");

super.onCreate();

}

@Override

public
void onStart(Intent intent, int startId) {

//
TODO Auto-generated method stub

super.onStart(intent, startId);

Log.i("",
"onStart");

}

@Override

public
void onDestroy() {

Log.i("",
"onDestroy");

    }

@Override

    public
int onStartCommand(Intent intent,
int flags, int startId) {

Log.i("",
this.toString() +
" ServiceDemo onStartCommand");

        return
super.onStartCommand(intent, flags, startId);

    }

}

在AndroidManifest.xml中添加Service的引用。

<service
android:name="com.example.smsreciver.Myservice"

            android:enabled="true">

        </service>

在activity中启动service

Intent intent = new Intent(MainActivity.this,  Myservice.class);

MainActivity.this.startService(intent);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Service