需要有关如何在后台永远运行Android服务的代码示例,即使设备正在休眠,如Whatsapp?

zee*_*han 27 service android background-process alarmmanager

我已经尝试了各种方法来实现这一目标,但我的服务最终会被杀死.

我想用AlarmManager每隔一小时触发一次课.即使设备处于休眠状态,它也应该发出闪烁的LED警报,振动或声音.无论如何,它应该永远运行.

我注意到Whatsapp一直在运行,即使我杀死所有正在运行的应用程序并清除内存,让设备进入睡眠状态,但仍然Whatsapp接收消息并提醒我.他们是怎么做到的?我想对我的应用做同样的事情.

zee*_*han 27

自从我发布这个问题以来,我已经将此解决方案实现了两种不同的方法到多个应用程序


方法1

此摘录来自我使用推送通知的应用程序,该通知需要立即唤醒设备的呼叫.我在这里做的是

  1. 使用WAKE_LOCK权限和
  2. 使用Wakelocker抽象类
  3. 根据需要在Activity中使用它:

表现:

<uses-permission android:name="android.permission.WAKE_LOCK" />
Run Code Online (Sandbox Code Playgroud)

WakeLocker类:

public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;

public static void acquire(Context context) {
    if (wakeLock != null) wakeLock.release();

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
            PowerManager.ACQUIRE_CAUSES_WAKEUP |
            PowerManager.ON_AFTER_RELEASE, "WakeLock");
    wakeLock.acquire();
}

public static void release() {
    if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}
Run Code Online (Sandbox Code Playgroud)

活动类示例:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Waking up mobile if it is sleeping
        WakeLocker.acquire(getApplicationContext());
        // do something
        WakeLocker.release();
}
Run Code Online (Sandbox Code Playgroud)

方法2

当您想让Android控制唤醒时,最好,并可以定期唤醒您的代码.只需使用AlarmManager定期调用Service类.以下是我的LifeLog24应用程序中的一些代码:

主要活动

Intent ll24 = new Intent(context, AlarmReceiverLifeLog.class);
    PendingIntent recurringLl24 = PendingIntent.getBroadcast(context, 0, ll24, PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarms.setRepeating(AlarmManager.RTC_WAKEUP, first_log.getTime(), AlarmManager.INTERVAL_HOUR, recurringLl24); // Log repetition
Run Code Online (Sandbox Code Playgroud)

报警类

public class AlarmReceiverLifeLog extends BroadcastReceiver {

    private static final String TAG = "LL24";
    static Context context;

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.v(TAG, "Alarm for LifeLog...");

        Intent ll24Service = new Intent(context, LifeLogService.class);
        context.startService(ll24Service);
    }
    }
Run Code Online (Sandbox Code Playgroud)

和LifeLogService.class是我做的事情.在这种情况下,警报每小时唤醒一次,并触发BroadcastReceiver,而BroadcastReceiver则返回运行服务.还有更多的东西,以确保服务不会运行两次等等,但你明白了它是如何完成的.并且AlarmManager实际上是最好的方法,因为您不必担心电池使用等,Android会定期唤醒您的服务.


小智 8

这很简单.
步骤:
1.创建一个Service类. 2.在onDestroy服务方法中创建
一个BroadcastReceiver类
3.call BroadReceiver 4. 再次在BroadReceiver类的onReceive方法启动服务.

这是代码

清单文件: `

<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">

    <activity android:name=".LauncherActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service
        android:name=".utilities.NotificationService"
        android:enabled="true">

    </service>

    <receiver
        android:name=".utilities.RestartService"
        android:enabled="true"
        android:exported="true"
        android:label="RestartServiceWhenStopped"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="RestartService" />
        </intent-filter>
    </receiver>
</application>
Run Code Online (Sandbox Code Playgroud)

`

服务类

public class NotificationService extends Service {
    public NotificationService() {
    }

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

   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
       super.onStartCommand(intent, flags, startId);
       return START_STICKY;
   }

   @Override
   public void onDestroy() {
       super.onDestroy();
       Intent restartService = new Intent("RestartService");
       sendBroadcast(restartService);
  }
}
Run Code Online (Sandbox Code Playgroud)

BroadcastReceiver类

public class RestartService extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {

         context.startService(new Intent(context,NotificationService.class));
     }
 }
Run Code Online (Sandbox Code Playgroud)

  • 如果系统资源不足,则无法保证调用onDestroy (4认同)
  • 不要使用此答案,在系统终止服务时并不总是调用onDestroy。 (2认同)