---
title: "编写安卓无界面后台程序 开机自启动服务"
author: "netspook"
date: "2011-12-04T22:04:42Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2012-06-04T22:47:44Z"
id: 1291236
url: "https://netspook.iteye.com/blog/1291236"
---

今天写了一个安卓小程序，这个程序没有界面，也不会在桌面创建应用程序图标

当然，在“设置”中的应用程序管理是可以看到的，也可以把这个应用程序删除

简单的说，这是一个没有界面的后台运行的应用程序

而且，还有一功能：开机自启动，启动运行一个服务

程序结构非常简单，两个类，一个是service的扩展类，一个是BroadcastReceiver扩展类

service扩展类：

```
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class TestService extends Service{   

    public void onCreate(){   
        super.onCreate(); 
        Log.d("AAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAAAAA");
        Toast.makeText(getApplicationContext(), "默认Toast样式",
              Toast.LENGTH_LONG).show();
    }   
       
    public IBinder onBind(Intent intent){   
     Log.d("BBBBBBBBBBBBBBBBBBB", "BBBBBBBBBBBBBBBBBBBBBBB"); 
     Toast.makeText(getApplicationContext(), "不默认Toast样式",
             Toast.LENGTH_LONG).show();
        return null;   
    }   
} 
```

 

 

BroadcastReceiver扩展类：

```
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class BootReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context arg0, Intent arg1) {
  // TODO Auto-generated method stub

  Log.d("WWWWWWWWWWWWWWWWWWWWW", "WWWWWWWWWWWWWWWWWWWWWWWW");
  Intent mBootIntent = new Intent(arg0, TestService.class);
  arg0.startService(mBootIntent);
  Log.d("CCCCCCCCCCCCCCCCCCCCC", "CCCCCCCCCCCCCCCCCCCCCCCC");
 }
}
```

 

 

配置文件：

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;manifest xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
package="com.tyq"  
android:versionCode="1"  
android:versionName="1.0" &gt;

&lt;application  
android:icon="@drawable/ic\_launcher"  
android:label="@string/app\_name" &gt;  
&lt;service android:name=".TestService"&gt;&lt;/service&gt;  
&lt;receiver android:name=".BootReceiver"&gt;  
&lt;intent-filter&gt;  
&lt;action android:name="android.intent.action.BOOT\_COMPLETED" /&gt;  
&lt;/intent-filter&gt;  
&lt;/receiver&gt;  
&lt;/application&gt;

&lt;uses-permission android:name="android.permission.RECEIVE\_BOOT\_COMPLETED" /&gt;  
&lt;uses-sdk android:minSdkVersion="10" /&gt;  
&lt;/manifest&gt;