首页 文章

Android - 启动时启动服务

提问于
浏览
103

我需要在启动时启动服务 . 我搜索了很多 . 他们在谈论Broadcastreceiver . 由于我是Android开发的新手,我没有清楚地了解Android上的服务 . 请提供一些源代码 .

8 回答

  • 4

    你应该注册BOOT_COMPLETE以及REBOOT

    <receiver android:name=".Services.BootComplete">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <action android:name="android.intent.action.REBOOT"/>
            </intent-filter>
        </receiver>
    
  • 1
  • 32

    你的接收者:

    public class MyReceiver extends BroadcastReceiver {   
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
         Intent myIntent = new Intent(context, YourService.class);
         context.startService(myIntent);
    
        }
    }
    

    你的AndroidManifest.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.broadcast.receiver.example"
          android:versionCode="1"
          android:versionName="1.0">
        <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
    
            <activity android:name=".BR_Example"
                      android:label="@string/app_name">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
        <!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
            <receiver android:name=".MyReceiver" android:enabled="true" android:exported="false">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED"/>
                </intent-filter>
            </receiver>
    
        </application>
    
        <!-- Adding the permission -->
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    
    </manifest>
    
  • 94

    可以注册您自己的应用程序服务,以便在设备启动时自动启动 . 例如,当您想要从http服务器接收推送事件并希望在新事件发生时立即通知用户时,您需要这样做 . 用户不必在服务开始之前手动启动活动......这非常简单 . 首先给你的应用程序RECEIVE_BOOT_COMPLETED权限 . 接下来,您需要注册BroadcastReveiver . 我们称之为BootCompletedIntentReceiver . 您的Manifest.xml现在应该如下所示:<manifest xmlns:android =“http://schemas.android.com/apk/res/android”
    包= “com.jjoe64”>
    <uses-permission android:name =“android.permission.RECEIVE_BOOT_COMPLETED”/>
    <应用>
    <receiver android:name =“ . BootCompletedIntentReceiver”>
    <意图滤波器>
    <action android:name =“android.intent.action.BOOT_COMPLETED”/>
    </意图滤波器>
    </接收机>
    <service android:name =“ . BackgroundService”/>
    </应用>
    </清单>
    作为最后一步,您必须实现Receiver . 这个接收器只是启动你的后台服务 . 包com.jjoe64;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.preference.PreferenceManager;

    import com.jjoe64.BackgroundService;

    public class BootCompletedIntentReceiver扩展BroadcastReceiver {
    @覆盖
    public void onReceive(Context context,Intent intent){
    if(“android.intent.action.BOOT_COMPLETED”.equals(intent.getAction())){
    Intent pushIntent = new Intent(context,BackgroundService.class);
    context.startService(pushIntent);
    }
    }
    }

    来自http://www.jjoe64.com/2011/06/autostart-service-on-device-boot.html

  • 191

    这里发布的大多数解决方案都缺少一个重要的部分:在没有唤醒锁定的情况下执行它会导致服务在完成处理之前被杀死的风险 . 在另一个线程中看到这个解决方案,也在这里回答 .

    由于在api 26中不推荐使用WakefulBroadcastReceiver,因此建议 for API Levels below 26

    您需要获得唤醒锁定 . 幸运的是,Support library gives us a class这样做:

    public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // This is the Intent to deliver to our service.
            Intent service = new Intent(context, SimpleWakefulService.class);
    
            // Start the service, keeping the device awake while it is launching.
            Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
            startWakefulService(context, service);
        }
    }
    

    然后,在您的服务中,确保释放唤醒锁:

    @Override
        protected void onHandleIntent(Intent intent) {
            // At this point SimpleWakefulReceiver is still holding a wake lock
            // for us.  We can do whatever we need to here and then tell it that
            // it can release the wakelock.
    
    ...
            Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
            SimpleWakefulReceiver.completeWakefulIntent(intent);
        }
    

    不要忘记添加WAKE_LOCK权限并在清单中注册您的接收者:

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    
    ...
    
    <service android:name=".SimpleWakefulReceiver">
        <intent-filter>
            <action android:name="com.example.SimpleWakefulReceiver"/>
        </intent-filter>
    </service>
    
  • 0

    还要在Manifest中注册您创建的服务,并使用-enate权限

    <application ...>
       <service android:name=".MyBroadcastReceiver">
            <intent-filter>
                <action android:name="com.example.MyBroadcastReciver"/>
            </intent-filter>
       </service>
    </application>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    

    然后在braod cast Reciever中打电话给你的服务

    public class MyBroadcastReceiver extends BroadcastReceiver 
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            Intent myIntent = new Intent(context, MyService.class);
            context.startService(myIntent);
        }
    }
    
  • 15

    首先在manifest.xml文件中注册一个接收器:

    <receiver android:name="com.mileagelog.service.Broadcast_PowerUp" >
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>
    

    然后为这个接收器写一个广播,如:

    public class Broadcast_PowerUp extends BroadcastReceiver {
    
      @Override
      public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
    
        if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
            Toast.makeText(context, "Service_PowerUp Started",
                    Toast.LENGTH_LONG).show();
    
    
        } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
    
    
    
            Toast.makeText(context, "Service_PowerUp Stoped", Toast.LENGTH_LONG)
            .show();
        }
      }
    }
    
  • -1

    Pls check JobScheduler for apis above 26

    WakeLock 是最好的选择,但如果你认为api水平高于26,那么它是 deprecated in api level 26 请检查this link
    https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html#startWakefulService(android.content.Context,%20android.content.Intent)

    它说

    从Android O开始,后台检查限制使这个类不再普遍有用 . (从收到广播开始服务通常是不安全的,因为你没有任何保证你的应用程序在此时处于前台,因此允许这样做 . )相反,开发人员应该使用android . app.job.JobScheduler用于安排作业,这并不要求应用程序在执行此操作时保持唤醒锁定(系统将负责为作业保持唤醒锁定) .

    所以它说cosider JobScheduler
    https://developer.android.com/reference/android/app/job/JobScheduler

    如果要做某事而不是开始并保留它,你可以收到广播ACTION_BOOT_COMPLETED

    如果不是关于前台请检查辅助功能服务是否可以

    另一个选择是从广播接收器启动一个活动,并在onCreate()内启动服务后完成它,因为较新的Android版本不允许从接收器启动服务

相关问题