zoukankan      html  css  js  c++  java
  • Android 创建单独的服务运行在后台(无界面)

    今天项目有个需求是,开启一个服务单独运行在后台,而且还不能有界面,在度娘搜索了一圈也没发现可以完美解决的方法,然后自己尝试解决的方法,开始的思路是,把界面干掉,也就是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>

    运行程序,服务开启了,界面也不显示,完美解决了后台启动服务的进程。

    原文链接:https://blog.csdn.net/a704225995/article/details/56481934

  • 相关阅读:
    解决spring boot JavaMailSender部分收件人错误导致发送失败的问题
    Linux设备驱动开发基础--内核定时器
    Linux中断分层--工作队列
    Linux中断分层--软中断和tasklet
    深入理解函数线程安全与可重入
    Linux中断处理流程
    Linux混杂设备驱动--按键设备驱动
    Linux字符设备驱动--Led设备驱动
    Linux字符设备简单示例
    Linux内核硬件访问技术
  • 原文地址:https://www.cnblogs.com/Ph-one/p/13254649.html
Copyright © 2011-2022 走看看