android startservice无法启动服务

1、android startservice无法启动服务

之前MainActivity.java中启动service源代码如下:

    private void startMyService()
    {

        //启动Service处理任务
        Intent intent2 = new Intent(this, SmartCamService.class);


        Log.d("mainactivity》》","启动服务"+MainActivity.this.startService(intent2));

    }

配置文件AndroidMainfest.xml代码如下:

   <application

        android:allowBackup="true"
        android:icon="@mipmap/cap"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".main.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

    </application>

这样运行老是启动不了服务,日志老是返回NULL

3、解决办法:

在配置文件中加入如下代码:

 <application

        android:allowBackup="true"
        android:icon="@mipmap/cap"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".main.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:name=".service.SmartCamService"
            android:label="SmartCamService"
            android:enabled="true"
            >
            <intent-filter>
                <action android:name="android.intent.action.RESPOND_VIA_MESSAGE"  />

            </intent-filter>
        </service>

    </application>


4、然后在再在MainActivity.java中加入如下代码:

    private void startMyService()
    {

        //启动Service处理任务
        Intent intent2 = new Intent(this, SmartCamService.class);
        intent2.setAction("android.intent.action.RESPOND_VIA_MESSAGE");

        Log.d("mainactivity》》","启动服务"+MainActivity.this.startService(intent2));

    }


5、现在启动程序,查看后台就会发现服务已经启动。

6、欢迎各位网友多多指教。

原文地址:https://www.cnblogs.com/ywf520/p/6764347.html