首页 > 解决方案 > BroadcastReceiver 和 FLAG_INCLUDE_STOPPED_PACKAGES

问题描述

下午好 !

我完全糊涂了:当手机重新启动时,接收器应该启动服务。应用程序是否从未启动?把这面旗帜放在哪里?

BootBroadcast.java:

package by.minsk.davydov.checkcell;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class BootBroadcast extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Broadcast Intent Detected !",
                Toast.LENGTH_LONG).show();

        context.startService(new Intent(context, check.class));
    }
}

清单.xml:

<application
    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">
    <receiver android:name=".BootBroadcast" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
    <service android:enabled="true" android:exported="true" android:name=".check"/>
</application>

检查.java:

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

public class check extends Service {
    final String TAG = "myLogs";
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "Start check !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        Intent intent = new Intent();
        intent.setAction("by.minsk.davydov.checkcell");
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        sendBroadcast(intent);
    }
    public IBinder onBind(Intent intent) {
        return null;
    } // arg0
}

标签: javaandroid

解决方案


将清单中的接收者更改为:

<receiver
    android:name=".BootBroadcast"
    android:enabled="true"
    android:exported="true">
    <intent-filter>
         <action android:name="android.intent.action.BOOT_COMPLETED" />
         <action android:name="android.intent.action.QUICKBOOT_POWERON" />
    </intent-filter>
</receiver>

您的应用需要在安装后(至少)运行一次才能接收启动通知

Intent 由 Android 发送给您,您无法选择说明此 Intent 中包含哪些捆绑包。


推荐阅读