java - 当应用程序关闭并重新启动时,后台服务计数循环以双倍速度运行
问题描述
我在后台服务类中实现了一个简单的计数程序,它在一秒钟后增加变量。它还显示了在更新服务数据后的主要活动中的数据。但主要问题是,当我关闭应用程序时,它仍然在后台运行,但是当我再次启动它时,计数速度增加意味着变量值在 1 秒内变化 2 3 次。如果我在大约 1 分钟后启动应用程序,速度会快 10 到 20 倍。我不知道程序中的问题是什么。
我的服务等级
package com.darkcoderz.backgroundservices;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.Looper;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.JobIntentService;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.util.logging.Handler;
public class BgService extends Service {
int i=0;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(i<1000)
{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
sendData(i);
}
stopForeground(true);
stopSelf();
}
});
thread.start();
return START_STICKY;
}
private void sendData(int idata) {
Intent intent = new Intent("donorrams");
intent.putExtra("hello",idata);
sendBroadcast(intent);
}
private void showNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
NotificationChannel channel = new NotificationChannel("donation","donation", NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
Intent result = new Intent(this,BgService.class);
PendingIntent pendresult = PendingIntent.getActivity(this,1,result,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"donation")
.setContentTitle("DonorRams")
.setAutoCancel(true)
.setContentText("We start processing on your donation")
.setContentIntent(pendresult);
Notification manager = builder.build();
//manager.notify(999,builder.build());
startForeground(123, manager);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
主要活动
package com.darkcoderz.backgroundservices;
import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private BroadcastReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent service = new Intent(MainActivity.this,BgService.class);
startService(service);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter intentFilter = new IntentFilter(
"donorrams");
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//extract our message from intent
TextView count = findViewById(R.id.count);
int msg_for_me = intent.getIntExtra("hello",0);
//Toast.makeText(context, ""+msg_for_me, Toast.LENGTH_SHORT).show();
count.setText(""+msg_for_me);
}
};
//registering our receiver
this.registerReceiver(mReceiver, intentFilter);
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//unregister our receiver
this.unregisterReceiver(this.mReceiver);
}
}
解决方案
private Thread thread;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
if (thread == null) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
setThread(null);
}
});
setThread(t);
t.start();
}
...
}
private synchronized void setThread(Thread thread) {
this.thread = thread;
}
推荐阅读
- c# - 如何在构成 DataTable 中的第 3 列的 2 列值之间添加空格?
- r - Multiple plots gives a blank PDF, data dimension error
- c++ - 不能在 C++ 中包含标头
- sql - 如何在后台保存 SQL 查询分析,同时仍向用户提供记录?
- android - android studio Jsoup 缺少内容
- triggers - 将服务挂钩的 Azure Devops IP 列入白名单
- java - 为什么在分配给临时变量的 for 循环值中不能按原样打印?
- javascript - 数据表:未捕获的类型错误:无法读取未定义的属性“唯一”
- java - How to configure a Gradle Java Platform to prefer the higher dependency version?
- angular - 如何使用 TranslateHttpLoader 从文件中加载翻译并动态添加更多翻译数据?