Android服务无法从BOOT上的JobIntentService开始 [英] Android Service not getting start from JobIntentService on BOOT

查看:113
本文介绍了Android服务无法从BOOT上的JobIntentService开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在OREO设备上运行服务,并且服务开始运行,因为它会监听 android.intent.action.BOOT_COMPLETED 意图。

I am trying to run a service on OREO device and service get started as it listens to android.intent.action.BOOT_COMPLETED intent.

以下是引导接收的广播接收器类:

Below is Boot Received Broadcast Reciever class:

public class ConnectionBOOTReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        MyIntentService.enqueueWork(context, new Intent());

    }

}

下面是我的IntentService类别:

Below is my IntentService Class:

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.JobIntentService;

public class MyIntentService extends JobIntentService {

    // Service unique ID
    static final int SERVICE_JOB_ID = 997;

    // Enqueuing work into this service.
    public static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, MyIntentService.class, SERVICE_JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        onHandleIntent(intent);
    }

    private void onHandleIntent(Intent intent) {

      startService(new Intent(this,MyBackgroundService.class));
        //Handling of notification goes here
    }
}

据我所知,有一些后台限制,我必须创建两个后台服务,一个是Foreground,另一个在后台运行。

As I know there is some Background limitation I have to create two background services one is Foreground and other one runs in the background.

后台服务代码:

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

import java.util.Timer;
import java.util.TimerTask;

public class MyBackgroundService extends Service {
    private static final String TAG = "MyBackgroundService";
    public int counter = 0;

    public MyBackgroundService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "NotifyingDailyService", Toast.LENGTH_LONG).show();
        Log.i("com.example.ss   ", "NotifyingDailyService");

        super.onStartCommand(intent, flags, startId);
        startTimer();
        return START_STICKY;
    }


    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        // send new broadcast when service is destroyed.
        // this broadcast restarts the service.

        stoptimertask();
    }

    private Timer timer;
    private TimerTask timerTask;
    long oldTime = 0;


    public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, to wake up every 1 second
        timer.schedule(timerTask, 1000, 1000); //
    }

    /**
     * it sets the timer to print the counter every x seconds
     */
    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                Log.i("in timer", "in timer ++++  " + (counter++));
            }
        };
    }

    /**
     * not needed
     */
    public void stoptimertask() {
        //stop the timer, if it's not already null
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }
}

前台服务代码:

public class MyForegroundBackgroundService extends Service {

    private Context context;
    public static final String NOTIFICATION_CHANNEL_ID = "10001";

    public MyForegroundBackgroundService() {
    }

    @Override
    public void onCreate(){
        super.onCreate();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            startMyOwnForeground();
        else
            startForeground(1, new Notification());
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        context = this;
        super.onStartCommand(intent, flags, startId);

        Intent intent1 = new Intent(this, MyForegroundBackgroundService.class);
        PendingIntent pintent = PendingIntent.getService(this, 0, intent1, 0);
        AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Calendar cal= Calendar.getInstance();
        alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);


        return START_STICKY;

    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startMyOwnForeground(){
        String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
        String channelName = "My Background Service";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
        chan.setLightColor(Color.BLUE);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        Notification notification = notificationBuilder.setOngoing(true)
                .setSmallIcon(R.mipmap.talentify_logo_red)
                .setContentTitle("App is running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }




    public void sendNotification(String message,Context context){
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.general_message_notfication);


        remoteViews.setTextViewText(R.id.message,message);
        Intent intent = new Intent();

        intent  = new Intent(context, HomeActivity.class);

        PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context,NOTIFICATION_CHANNEL_ID)
                .setSmallIcon(R.mipmap.talentify_logo_red)
                .setAutoCancel(true)
                .setContentIntent(pIntent)
                .setContent(remoteViews);
        NotificationManager notificationmanager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
        try {
            long[] pattern = new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400};
            builder.setVibrate(pattern);
            builder.setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.notification_sound));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            @SuppressLint("WrongConstant") NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Urgent", importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            builder.setChannelId(NOTIFICATION_CHANNEL_ID);
            notificationmanager.createNotificationChannel(notificationChannel);
        }


        notificationmanager.notify(0, builder.build());
    }
}

以下是我得到的例外:

  Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=test.MyApplication/.service.MyBackgroundService }: app is in background uid UidRecord{7e9d561 u0a158 TRNB idle procs:1 seq(0,0,0)}
        at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1536)
        at android.app.ContextImpl.startService(ContextImpl.java:1492)

如何从Boot Broadcast接收器启动服务?我该如何确保它应该始终保持运行?

How can I start my service from Boot Broadcast receiver? How can I make sure that it should keep running always?

推荐答案

由于Android O Apps在应用程序运行时不再能够运行后台服务在后台。您将需要更新到前台服务或迁移到作业。我建议使用Evernote Android Job库来简化Jobs的工作和向后兼容性。

Since Android O Apps can no longer run Background Services while the App is in the Background. You will need to either update to a foreground service or migrate to jobs. I recommend the Evernote Android Job library to simplify working with Jobs and backwards compatibility.

这篇关于Android服务无法从BOOT上的JobIntentService开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆