重新启动后,Android服务并非始终启动

时间:2018-12-04 16:42:21

标签: android service broadcastreceiver reboot

我想在重新启动后启动服务。我的问题是,这种情况不会每次都发生(至少前20分钟)。我已经研究了许多关于stackoverflow的问题,并尝试了许多提供的解决方案,但是有时该服务在重新启动后不会自动启动。 另外,我还必须为Android O及以上版本的前台服务添加另一个参数。 有人可以给我任何建议吗?

AndroidManifest.xml

.... <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
    android:name=".App"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    >
    <activity
        android:name=".Activities.MainActivity"
        ....
    </activity>


    <activity
        ...
    </activity>
    <receiver android:name=".Helpers.BootCompletedIntentReceiver" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
     <!--  I think that this is also not necessery     <category android:name="android.intent.category.DEFAULT" /> -->
            <action android:name="android.intent.action.QUICKBOOT_POWERON"/>
        </intent-filter>
    </receiver>
    <service
        android:name=".Services.myService"
        android:enabled="true"
        android:exported="true"></service>

</application>

广播接收器

package com.abc.Helpers;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Build;
    import android.support.v4.content.ContextCompat;
    import android.util.Log;
    import com.abx.Activities.MainActivity;
    import com.abc.Services.myService;
public class BootCompletedIntentReceiver extends BroadcastReceiver {

private static final String TAG = "MyBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
        Intent serviceIntent = new Intent(context, myService.class);
        serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ContextCompat.startForegroundService(context,serviceIntent);
        } else {
            context.startService(serviceIntent);
        }
    } 
}

我还在评论here中发现应将接收者注册到应用程序的活动中,这是Mainactivity中的代码。你同意吗?

     @Override
    protected void onCreate(Bundle savedInstanceState) {
...
final ComponentName onBootReceiver = new ComponentName(getApplication().getPackageName(), BootCompletedIntentReceiver.class.getName());
        if(getPackageManager().getComponentEnabledSetting(onBootReceiver) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
            getPackageManager().setComponentEnabledSetting(onBootReceiver,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
..
}

0 个答案:

没有答案