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

Android 创建单独的服务运行在后台(无界面)

2017-02-22 11:35 288 查看
今天项目有个需求是,开启一个服务单独运行在后台,而且还不能有界面,在度娘搜索了一圈也没发现可以完美解决的方法,然后自己尝试解决的方法,开始的思路是,把界面干掉,也就是activity,然后将开启Service的操作放在Application中,结果运行程序,在控制台报错了。



因为我把AndroidManifest.xml中的主Activity的配置给干掉了,而程序找不到应用的入口,所有就无法打开应用,这种方法行不通。

然后我就想,把Activity保留,但是我不给它 setContentView(......);也就是不给他设置布局文件,

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

System.out.println("MainActivity OnCreate()....");

System.out.println("准备开启服务");
Intent intent = new Intent(MainActivity.this,TestService.class);
startService(intent);
}
}

运行程序,程序打开了,服务也运行了,但是有个问题就是,界面也出来了,为什么呢?





原因是在AndroidManifest.xml中Application节点中这个这行代码android:theme="@style/AppTheme",既然是主题的问题导致界面的出现,那么是想android是否提供了不显示界面的主题?查找后问题终于解决了,解决方法:在清单文件中,主activity的配置中添加这行代码

android:theme="@android:style/Theme.NoDisplay"
代码:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoDisplay"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<service android:name="com.example.backgroundservice.TestService" >
</service>
</application>

我们还可以Ctrl+左键点进去看看这个主题是怎么写的:
<!-- Default theme for activities that don't actually display a UI; that
is, they finish themselves before being resumed. -->
<style name="Theme.NoDisplay">
<item name="android:windowBackground">@null</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@null</item>
<item name="android:windowDisablePreview">true</item>
<item name="android:windowNoDisplay">true</item>
</style>

运行程序,服务开启了,界面也不显示,完美解决了后台启动服务的进程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐