当应用关闭并再次启动时,后台服务计数循环以其两倍的速度运行

问题描述 投票:1回答:1

我在后台服务类中实现了一个简单的计数程序,它会在一秒钟后递增变量。它还会在有意更新服务数据后在主要活动中显示数据。但是主要的问题是,当我关闭应用程序时,它仍在后台运行,但是当我再次启动它时,计数速度的增加意味着变量值在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();
    }
}

MainActivity

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);
    }


}
java android android-service
1个回答
2
投票
    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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.