即使添加了startForegroundService和startForeground,服务也会在后台中断

时间:2018-12-17 02:54:22

标签: android service background

大师: 我的程序存在以下问题: 编译平台:android studio 3.2 测试动机:android 8.0 操作:按“主页”,使程序在后台运行。充电状态可以。如果不收费,则该服务将在大约一分钟后“失效”。我怎样才能使其更长寿?谢谢。附带的代码:

=========第一部分:活动分类(部分代码)

Intent i=new  Intent(this,RegistService.class); 
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
   this.startForegroundService(i);
} else {
   this.startService(i);
}

=========第二部分:服务等级

public class RegistService extends Service {
    Timer timer;
    int num=0;
    public static final String CHANNEL_ID_STRING = "test001";
    @Override
    public void onCreate() {
        super.onCreate();
        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel mChannel = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID_STRING, "test001", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(mChannel);
            Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID_STRING).build();
            startForeground(28, notification);
        }
    }
    @Override
    public void onStart(Intent intent, int startId) {
        TimerTask task = new TimerTask(){
            public void run(){
                num=num+1;
                Log.v(num+"count","test");
            }
        };
        timer = new Timer();
        timer.schedule(task, 1000,1000);
    }
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

0 个答案:

没有答案