32

我需要在应用程序启动后一直保持广播接收器运行。

这是在应用程序中注册此接收器的代码

    IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    BroadcastReceiver mReceiver = new ScreenEventsReceiver();
    registerReceiver(mReceiver, filter);

和接收器代码

public class ScreenEventsReceiver extends BroadcastReceiver {
     public static boolean wasScreenOn = true;

     @Override
     public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            wasScreenOn = false;
            Log.d("ScreenEventReceiver", "ON");
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            wasScreenOn = true;
            Log.d("ScreenEventReceiver", "ON");
        }
     }
}
4

7 回答 7

30

您可以使用服务

在主应用程序中启动/停止服务

Intent service = new Intent(context, MyService.class);
context.startService(service);
...
Intent service = new Intent(context, MyService.class);
context.stopService(service);

服务

public class MyService extends Service
{
 private static BroadcastReceiver m_ScreenOffReceiver;

 @Override
 public IBinder onBind(Intent arg0)
 {
  return null;
 }

 @Override
 public void onCreate()
 {
  registerScreenOffReceiver();
 }

 @Override
 public void onDestroy()
 {
  unregisterReceiver(m_ScreenOffReceiver);
  m_ScreenOffReceiver = null;
 }

 private void registerScreenOffReceiver()
 {
  m_ScreenOffReceiver = new BroadcastReceiver()
  {
   @Override
   public void onReceive(Context context, Intent intent)
   {
     Log.d(TAG, "ACTION_SCREEN_OFF");
     // do something, e.g. send Intent to main app
   }
  };
  IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
  registerReceiver(m_ScreenOffReceiver, filter);
 }
}
于 2013-05-29T22:05:45.290 回答
17

接受的答案不是我认为的实际答案。我会解释什么问题。我认为您正在华为、Oppo、Vivo、小米、华硕......或某些设备上测试您的应用程序。使用这些设备,如果我们关闭应用程序,它们也会关闭我们的广播接收器。所以这就是问题所在。(检查是否使用了像素关联模拟器)。我将解释如何解决这个问题。``

  • 我们会将我们的应用添加到受保护的应用列表中。操作系统只允许他们继续广播接收器活动。(将此数组声明复制到您的代码中)

    private static final Intent[] POWERMANAGER_INTENTS = {
        new Intent().setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")),
        new Intent().setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),
        new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),
        new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),
        new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),
        new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")),
        new Intent().setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),
        new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
        new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
        new Intent().setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
        new Intent().setComponent(new ComponentName("com.samsung.android.lool", "com.samsung.android.sm.ui.battery.BatteryActivity")),
        new Intent().setComponent(new ComponentName("com.htc.pitroad", "com.htc.pitroad.landingpage.activity.LandingPageActivity")),
        new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.MainActivity"))};
    
  • 将这些代码放入您的 onCreate 方法中。在这里,我使用共享首选项仅在第一次打开应用程序时检查它。

`

final SharedPreferences.Editor pref =    getSharedPreferences("allow_notify", MODE_PRIVATE).edit();    pref.apply(); final SharedPreferences sp =    getSharedPreferences("allow_notify", MODE_PRIVATE)`;


    if(!sp.getBoolean("protected",false)) {
        for (final Intent intent : POWERMANAGER_INTENTS)
            if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {

            AlertDialog.Builder builder  = new AlertDialog.Builder(this);
            builder.setTitle("Alert Title").setMessage("Alert Body")
                    .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            startActivity(intent);
                            sp.edit().putBoolean("protected",true).apply();

                        }
                    })
                    .setCancelable(false)
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .create().show();
            break;
于 2018-09-18T02:14:56.847 回答
2

如果您BroadcastReceiver在 Manifest 中声明,即使应用程序关闭/停止,它也将始终处于活动状态并被调用

于 2014-01-27T22:38:33.713 回答
2

如果您使用的是 Android 4.4.x,请小心,因为在关闭应用程序时存在会杀死后台服务的错误。我在 Android 4.4.2 中测试我的应用程序,我遇到了同样的问题。这里有一个详细的解释:

http://www.androidpolice.com/2014/03/07/bug-watch-stopping-apps-on-android-4-4-2-can-silently-kill-related-background-services-a-fix-正在路上/

于 2016-05-12T12:19:33.257 回答
2

您无法通过清单中声明的​​组件接收某些广播事件。

这些事件是

  • ACTION_BATTERY_CHANGED
  • ACTION_CONFIGURATION_CHANGED
  • ACTION_SCREEN_OFF (你正在玩这个事件)
  • ACTION_SCREEN_ON (你正在玩这个事件)
  • ACTION_TIME_TICK

参考https://developer.android.com/reference/android/content/Intent.html#ACTION_SCREEN_ON

因此,在您的特定事件中,您必须创建一个服务,并且您必须使用 Context.registerReceiver() 在服务 onCreate() 中显式注册您的事件。

对于其他事件,清单中的条目就足够了。

于 2018-02-03T10:54:42.360 回答
1

您可以启动在前台运行的服务。这是确保(大多数情况下)您的应用程序将获得事件的唯一方法。在来自操作系统的疯狂内存压力时,您的前台服务仍有可能被杀死(因此它不是万无一失的)。但是,如果您在前台启动服务,用户将看到一个持久通知,知道它一直在运行。

所以这个故事的寓意是,你真的需要一直监控屏幕关闭/开启事件吗?他们强迫您注册不在清单中的接收器的原因是他们不希望人们总是监视这些事件并减慢设备速度。你想达到什么目的?

于 2013-05-29T22:16:32.523 回答
0

我找到的最好方法是Foreground Services. 我只在我的服务中注册了我的广播接收器,onStartCommand()因为我希望我的服务需要始终运行,我返回了START_STICKY

这样,即使在从堆栈中终止应用程序后,我的广播接收器仍然存在。

在我的服务中使用以下代码

    @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("rht", "Received start id " + startId + ": " + intent);
    
            String input = intent.getStringExtra("inputExtra");
            createNotificationChannel();
            Intent notificationIntent = new Intent(this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    0, notificationIntent, 0);
            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("Foreground Service")
                    .setContentText(input)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setContentIntent(pendingIntent)
                    .build();
            startForeground(1, notification);
}

这就是我开始服务的方式

Intent serviceIntent = new Intent(this, SpeechServiceForeground.class);
ContextCompat.startForegroundService(this, serviceIntent);
于 2021-02-19T02:35:34.357 回答