首页 新闻 赞助 找找看

安卓service服务程序后台运行中断问题

0
悬赏园豆:20 [待解决问题]

各位大侠,你们好!
这几天碰到一个后台服务程序问题,代码如下。

 问题:插上充电器时,测试运行一切正常。 但是拔掉充电器,只能运行一分钟左右。
 编程平台:android studio 3.2
 测试手机:android 8.0 (华为mate9)
 测试方法:运行后,按home键,让程序在后台运行
 
 麻烦大侠把我想想办法。多谢各位了。 

第一步:在activity的 onCreate 添加代码(部分代码)
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, "电话录音", 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) {
    // TODO Auto-generated method stub
    return null;
}
@Override
public void onDestroy() {
    super.onDestroy();
}

}

heighteen的主页 heighteen | 初学一级 | 园豆:184
提问于:2018-12-16 19:43
< >
分享
所有回答(1)
0

应该是手机问题, 不是软件问题

heighteen | 园豆:184 (初学一级) | 2018-12-18 22:53
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册