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

android开机启动无界面服务线程

2012-05-04 11:09 627 查看
http://www.yoyong.com/archives/450

android的开机启动某项功能很常见操作。很多时候我们往往只是需要开机启动一项服务,而不是将整个应用程序开启。这个时候只是需要启动一个service的服务就可以达到效果。开启一项后台服务后,我们还应该对该项服务进行控制,例如停止该线程服务。停止该服务可以按照一定的条件让服务线程自动关闭,也可以人为的手动关闭。

下面要实现以上这样的功能。

步骤包括:

1.建立一个android的项目,并且创建一个主要的Activity类(NoUIRebootDemoActivity.java )该类只有一个Button按钮,用来手动停止后台服务线程的。

2.创建一个继承BroadcastReceiver的广播类(TimerReceiver.java),该类通知Service类执行相应的代码。

注册receiver:

view plaincopy
to clipboardprint?

<receiver android:name=".TimerReceiver">  

<intent-filter>  

<action android:name="android.intent.action.BOOT_COMPLETED"/>  

<category android:name="android.intent.category.HOME" />  

</intent-filter>  

</receiver>  

3.创建一个继承Service类(TimerService.java ),该类主要执行后台的操作。这里主要执行一个定时打印时间代码的功能,并且执行三次后停止服务,并重写Service的onDestroy()方法,取消定时器,停止执行Service。

注册 service:

view plaincopy
to clipboardprint?

<service android:name ="TimerService" />  

在手动调用停止线程服务之前,可以判断当前的线程服务是否存在,如果存在,则停止该服务线程。

1.NoUIRebootDemoActivity .java

view plaincopy
to clipboardprint?

package com.NoUIRebootDemo.main;  

  

import java.util.List;  

  

import android.app.Activity;  

import android.app.ActivityManager;  

import android.app.ActivityManager.RunningServiceInfo;  

import android.content.Context;  

import android.content.Intent;  

import android.os.Bundle;  

import android.view.View;  

import android.view.View.OnClickListener;  

import android.widget.Button;  

  

public class NoUIRebootDemoActivity extends Activity {  

/** Called when the activity is first created. */  

@Override  

public void onCreate(Bundle savedInstanceState) {  

super.onCreate(savedInstanceState);  

setContentView(R.layout.main);  

Button stop = (Button) findViewById(R.id.stop);  

stop.setOnClickListener(stopClick);  

}  

  

// 事件响应  

OnClickListener stopClick = new OnClickListener() {  

  

@Override  

public void onClick(View v) {  

// TODO Auto-generated method stub  

// 如果服务线程存在  

if (isServiceRun(NoUIRebootDemoActivity.this)) {  

Intent s = new Intent(NoUIRebootDemoActivity.this,  

TimerService.class);  

NoUIRebootDemoActivity.this.stopService(s);  

System.out.println("服务线程手动停止");  

}  

}  

};  

  

// 判断服务线程是否存在  

public static boolean isServiceRun(Context context) {  

ActivityManager am = (ActivityManager) context  

.getSystemService(Context.ACTIVITY_SERVICE);  

List<RunningServiceInfo> list = am.getRunningServices(30);  

for (RunningServiceInfo info : list) {  

if (info.service.getClassName().equals(  

"com.NoUIRebootDemo.main.TimerService")) {  

return true;  

}  

}  

return false;  

}  

}  

2.TimerReceiver .java

view plaincopy
to clipboardprint?

package com.NoUIRebootDemo.main;  

  

import android.content.BroadcastReceiver;  

import android.content.Context;  

import android.content.Intent;  

  

public class TimerReceiver extends BroadcastReceiver {  

  

@Override  

public void onReceive(Context context, Intent intent) {  

// TODO Auto-generated method stub  

// 启动Service  

Intent s = new Intent(context, TimerService.class);  

context.startService(s);  

System.out.println("Receiver start");  

}  

}  

3.TimerService .java

view plaincopy
to clipboardprint?

package com.NoUIRebootDemo.main;  

  

import java.text.SimpleDateFormat;  

import java.util.Date;  

import java.util.Timer;  

import java.util.TimerTask;  

  

import android.app.Service;  

import android.content.Intent;  

import android.os.IBinder;  

import android.util.Log;  

  

public class TimerService extends Service {  

  

// 定时器  

private Timer mTimer;  

private TimerTask mTimerTask;  

private int i = 0;  

  

@Override  

public IBinder onBind(Intent intent) {  

// TODO Auto-generated method stub  

return null;  

}  

  

@Override  

public void onCreate() {  

super.onCreate();  

// 执行的Service  

// 定时器执行  

mTimer = new Timer();  

mTimerTask = new TimerTask() {  

@Override  

public void run() {  

// 打印出时间  

Log.d("AndroidTimerDemo", "timer:" + formatDate());  

// 这里设置一个自己停止的功能  

if (i > 2) {  

Intent s = new Intent(TimerService.this,  

TimerService.class);  

stopService(s);  

System.out.println("服务线程自动停止");  

}  

System.out.println("服务线程执行次数:" + i);  

i++;  

}  

};  

mTimer.schedule(mTimerTask, 10000, 10000);  

}  

  

@Override  

public void onDestroy() {  

// TODO Auto-generated method stub  

System.out.println("onDestroy");  

mTimer.cancel();  

super.onDestroy();  

}  

// 输出时间  

public String formatDate() {  

SimpleDateFormat dateFormat = new SimpleDateFormat(  

"yyyy-MM-dd HH:mm:ss");  

String s = dateFormat.format(new Date());  

return s;  

}  

}  

4.main.xml

view plaincopy
to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>  

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

android:orientation="vertical"  

android:layout_width="fill_parent"  

android:layout_height="wrap_content" >  

<Button android:id="@+id/stop"  

android:layout_width="fill_parent"  

android:layout_height="wrap_content"  

android:text="手动停止服务" />  

</LinearLayout>  

5.AndroidManifest.xml

view plaincopy
to clipboardprint?

<?xml version="1.0" encoding="utf-8"?>  

<manifest xmlns:android="http://schemas.android.com/apk/res/android"  

package="com.NoUIRebootDemo.main"  

android:versionCode="1"  

android:versionName="1.0">  

<uses-sdk android:minSdkVersion="7" />  

<application android:icon="@drawable/icon" android:label="@string/app_name">  

<activity android:name=".NoUIRebootDemoActivity"  

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 ="TimerService" />  

<receiver android:name=".TimerReceiver">  

<intent-filter>  

<action android:name="android.intent.action.BOOT_COMPLETED"/>  

<category android:name="android.intent.category.HOME" />  

</intent-filter>  

</receiver>  

</application>  

</manifest>  

需要注意一点:每次修改程序,都要先执行一次该程序(安装apk到模拟器),然后关闭模拟器,重新启动模拟器。

下图可以看到在后台运行的服务程序



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息