如何防止Android服务中的代码运行两次
我正在尝试创建一个用于检查数据和推送通知的服务。停止呼叫后,我再次遇到呼叫服务问题。好像有2个或更多的服务实例正在运行(//我的代码在这里运行了两次,在停止和启动后调用了两次通知,我对它进行了注释,因为它是一个长代码xD)。我怎样才能预防它 根据我找到的一些答案,我尝试将线程放在onCreate()中,但没有效果 这是我的密码:如何防止Android服务中的代码运行两次,android,service,background,Android,Service,Background,我正在尝试创建一个用于检查数据和推送通知的服务。停止呼叫后,我再次遇到呼叫服务问题。好像有2个或更多的服务实例正在运行(//我的代码在这里运行了两次,在停止和启动后调用了两次通知,我对它进行了注释,因为它是一个长代码xD)。我怎样才能预防它 根据我找到的一些答案,我尝试将线程放在onCreate()中,但没有效果 这是我的密码: public class CheckDataAndPushNotificationService extends Service { public CheckDataA
public class CheckDataAndPushNotificationService extends Service {
public CheckDataAndPushNotificationService() {
}
private String token;
ArrayList<UsefulRequestData> oldData;
ArrayList<UsefulRequestData> newData;
LocalBroadcastManager localBroadcastManager;
ApiUtil apiUtil;
String notificationNewRequest = "Có yêu cầu mới.";
String notificationCancelRequest = "Có yêu cầu đã bị hủy.";
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
newData = new ArrayList<>();
localBroadcastManager = LocalBroadcastManager.getInstance(this);
apiUtil = new ApiUtil(this);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
// my code here
}, 0, 5000);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
public void createNotification(String message) {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("RequestNotification", "RequestNotification", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Use to notify if you have new or cancel request.");
notificationManager.createNotificationChannel(channel);
}
Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "RequestNotification")
.setSmallIcon(R.mipmap.ic_app_icon) // notification icon
.setContentTitle("XCaller") // title for notification
.setContentText(message)// message for notification
.setAutoCancel(true)// clear notification after click
.setSound(defaultSound);
Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
notificationManager.notify(0, mBuilder.build());
}
公共类CheckDataAndPushNotificationService扩展了服务{
public CheckDataAndPushNotificationService(){
}
私有字符串令牌;
ArrayList oldData;
arraylistnewdata;
LocalBroadcastManager LocalBroadcastManager;
ApiUtil-ApiUtil;
String notificationNewRequest=“Cóyêu Cầ嗯ới、 “;
String notificationCancelRequest=“Cóyêu Cầuđđđbị Hủy、 “;
@凌驾
公共IBinder onBind(意向){
//TODO:将通信通道返回到服务。
抛出新的UnsupportedOperationException(“尚未实现”);
}
@凌驾
public void onCreate(){
newData=newarraylist();
localBroadcastManager=localBroadcastManager.getInstance(this);
apiUtil=新的apiUtil(本);
定时器=新定时器();
timer.scheduleAtFixedRate(新TimerTask(){
//我的代码在这里
}, 0, 5000);
super.onCreate();
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId){
返回开始时间不粘;
}
公共void createNotification(字符串消息){
NotificationManager NotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION\u服务);
if(android.os.Build.VERSION.SDK\u INT>=android.os.Build.VERSION\u code.O){
NotificationChannel=new NotificationChannel(“RequestNotification”、“RequestNotification”、NotificationManager.IMPORTANCE\u默认值);
channel.setDescription(“用于通知您是否有新的或取消的请求”);
notificationManager.createNotificationChannel(频道);
}
Uri defaultSound=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_通知);
NotificationCompat.Builder mBuilder=新建NotificationCompat.Builder(getApplicationContext(),“RequestNotification”)
.setSmallIcon(R.mipmap.ic_app_icon)//通知图标
.setContentTitle(“XCaller”)//通知的标题
.setContentText(消息)//用于通知的消息
.setAutoCancel(true)//单击后清除通知
.setSound(默认声音);
Intent Intent=新的Intent(getApplicationContext(),SplashActivity.class);
pendingent pi=pendingent.getActivity(this,0,intent,pendingent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
notificationManager.notify(0,mBuilder.build());
}
}您需要使用
IntentService
。它非常适合你的需要。它会自动为您发送给它的工作创建单独的线程
从
IntentService是处理异步服务的基类
按需请求(表示为意图)。客户端发送请求
通过Context.startService(Intent)调用;该服务按以下方式启动:
需要时,使用辅助线程依次处理每个意图,然后停止
当它没有工作的时候,它自己
这种“工作队列处理器”模式通常用于卸载任务
从应用程序的主线程。IntentService类的存在是为了
简化此模式并注意力学。要使用它,
扩展IntentService并实现
onHandleIntent(android.content.Intent)。IntentService将收到
启动工作线程,并根据需要停止服务
所有请求都在单个工作线程上处理——它们可以作为
只要有必要(并且不会阻塞应用程序的主循环),
但一次只处理一个请求
您需要使用
IntentService
。它非常适合你的需要。它会自动为您发送给它的工作创建单独的线程
从
IntentService是处理异步服务的基类
按需请求(表示为意图)。客户端发送请求
通过Context.startService(Intent)调用;该服务按以下方式启动:
需要时,使用辅助线程依次处理每个意图,然后停止
当它没有工作的时候,它自己
这种“工作队列处理器”模式通常用于卸载任务
从应用程序的主线程。IntentService类的存在是为了
简化此模式并注意力学。要使用它,
扩展IntentService并实现
onHandleIntent(android.content.Intent)。IntentService将收到
启动工作线程,并根据需要停止服务
所有请求都在单个工作线程上处理——它们可以作为
只要有必要(并且不会阻塞应用程序的主循环),
但一次只处理一个请求
我通过重写方法onDestroy()解决了这个问题,并取消了计时器。调用stopService()时,onDestroy()将运行
@Override
public void onDestroy() {
timer.cancel();
super.onDestroy();
}
我通过重写方法onDestroy()解决了这个问题,并取消了计时器。调用stopService()时,onDestroy()将运行
@Override
public void onDestroy() {
timer.cancel();
super.onDestroy();
}