现在的位置: 首页 > 综合 > 正文

Activity启动Service

2014年09月28日 ⁄ 综合 ⁄ 共 2363字 ⁄ 字号 评论关闭

这篇博客比较简单,但为了在博客里,关于Service内容相对全面,所以还是贴出来了,请各位不要拍砖哈.

本篇博客主要内容是Activity启动Service,并在Service中启动线程的简单实例:

Service是创建一次,启动多次,即使应用程序退出,Service也还在运行。

服务只能onCreate()和onDestroy()一次。

如果Activity没有绑定Service,则服务的生命周期如下:

onCreate -----> onStart() ------> onStart() -------> onStart ------>...................... onDestory()

第一步:建立服务类,该类继承Service类。

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
/**
 * 1.启动服务时,如果没有服务对象,那么做
 * (1)创建服务对象
 * (2)调用onCreate函数
 * (3)调用onStart函数
 * 2.服务可以被多次启动
 * 3.启动服务时,如果已经有服务对象,那么后台会直接调用onStart函数
 * 4.只要启动服务都会调用onStart函数.
 * 5.停止服务时,后台会先调用onDestroy函数,再销毁服务对象
 * */
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "onCreate...", 1).show();
System.out.println("onCreate()...");
}
//可以在该回调函数中开线程
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "onStart", 1).show();
System.out.println("onStart");

//new MyThread().start();

}
@Override
public void onDestroy() {
Toast.makeText(this, "onDestroy", 1).show();
System.out.println("onDestroy");
}
}

第二步:在manifest.xml文件中注册Service对象(四大组件都需要注册)

如果此处已经配置了action,其他应用程序可能通过该acttion来访问该服务。

-<service
android:name
=".MyService">
-<intent-filter>
 
<action android:name="aa.bb" />
    </intent-filter>
</service>







第三步:在Activity中启动Service
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
private Button start,stop;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);
        this.init();
    }
private void init() {
this.start = (Button) this.findViewById(R.id.startx);
this.stop = (Button) this.findViewById(R.id.stop);
this.start.setOnClickListener(this);
this.stop.setOnClickListener(this);
}
public void onClick(View v) {
Intent intent = new Intent();
// intent.setClass(this, MyService.class);
intent.setAction("aa.bb");

if(v==this.start) {
this.startService(intent);//启动服务
}else if(v==this.stop) {
// this.stopService(intent);//关闭服务
System.exit(0);
}
}
}

创建线程类

public class MyThread extends Thread {
public boolean on = false;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if(on==false) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(""+i);
}
}
}

抱歉!评论已关闭.