java - 服务在应用程序关闭时停止,而以前没有

标签 java android service handler bind

我正在创建一个应用程序,该应用程序使用 Service 中的处理程序在后台运行 24 小时计时器。 Service 应始终运行,即使应用完全关闭时也是如此。在 Timer 完全耗尽之前,Service 不应结束。最初它正在工作,即使应用程序完全关闭,Service 也会继续在后台运行,但突然间它无法正常工作。

这是我的服务的代码:

public class SetupTimerPC1 extends Service
{
Handler handler;
Database data;
Intent i, result;
runGraphics runG;
int bucketLevel = 1, bucketExpTotal = 0, totalWater = 0, bucketExp = 0;
float waterAmt = 0;
int timerCount = 0;
Notification notify;
Notification.Builder builder;
NotificationManager notificationManager;
PendingIntent pendingIntent;
@Override
public IBinder onBind(Intent intent) 
{
    return null;
}//end onBind function

@Override
public void onRebind(Intent intent)
{
    super.onRebind(intent);
}//end onRebing

@Override
public boolean onUnbind(Intent intent)
{
    return true;
}//end onUnbind

@Override
public void onCreate() 
{
    super.onCreate();

    //setup 24 hour timer
    handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(runnable, 600000); //600000 -> wait ten minutes then call runnable
}//end onCreate function

private Runnable runnable = new Runnable()
{
    public void run()
    {
        //get current bucket exp
        data = new Database(SetupTimerPC1.this);
        data.open();
        bucketExp = data.getBucketExp();
        data.close();

        //check experience for current level
        if (bucketExp < 3000)
        {
            bucketLevel = 1;
        }//end if
        else if (bucketExp > 3000 && bucketExp < 6000)
        {
            bucketLevel = 2;
        }//end else if
        else if (bucketExp > 6000 && bucketExp < 9000)
        {
            bucketLevel = 3;
        }//end else if
        else if (bucketExp > 9000 && bucketExp < 12000)
        {
            bucketLevel = 4;
        }//end else if
        else if (bucketExp > 12000)
        {
            bucketLevel = 5;
        }//end else if

        //give resource based on level
        if (bucketLevel == 1)
        {
            waterAmt += .2;
            bucketExp += 1;
        }//end if
        else if (bucketLevel == 2)
        {
            waterAmt += .4;
            bucketExp += 2;
        }//end else if
        else if (bucketLevel == 3)
        {
            waterAmt += .6;
            bucketExp += 3;
        }//end else if
        else if (bucketLevel == 4)
        {
            waterAmt += .8;
            bucketExp += 4;
        }//end else if
        else if (bucketLevel == 5)
        {
            waterAmt += 1.0;
            bucketExp += 5;
        }//end else if
        timerCount++;
        if (timerCount < 144)//144
        {
            handler.postDelayed(runnable, 600000); //600000
        }//end if
        else
        {
            //pull data
            data = new Database(SetupTimerPC1.this);
            data.open();
            bucketExpTotal = data.getBucketExp();
            totalWater = data.getWaterAmt();
            data.close();

            //add new data to old
            bucketExpTotal += bucketExp;
            totalWater += (int)waterAmt;

            //push data
            data.open();
            data.bucketExpEntry(bucketExpTotal);
            data.waterAmountEntry(totalWater);
            data.bucketLevelEntry(bucketLevel);
            data.close();

            //send notification that resources have been gained
            notifyUser();

            i.putExtra("polarCap1Stat", true);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
            handler.removeCallbacks(runnable);
        }//end else
    }//end run function
};//end runnable    

public void notifyUser()
{
    //notify user of resource gain 
    result = new Intent(this, runGraphics.class);
    pendingIntent = PendingIntent.getActivity(
        SetupTimerPC1.this, 
        0, 
        result, 
        Intent.FLAG_ACTIVITY_NEW_TASK);

    notify = new Notification.Builder(getApplicationContext())
         .setContentTitle("2023: Water Gained")
         .setContentText("Successfully extracted water.")
         .setTicker("2023")
         .setWhen(System.currentTimeMillis())
         .setContentIntent(pendingIntent)
         .setDefaults(Notification.DEFAULT_SOUND)
         .setAutoCancel(true)
         .setSmallIcon(R.drawable.alienicon)
         .build();

        notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notify);
}//end notifyUser

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    i = new Intent("polarCap1Status");
    i.putExtra("polarCap1Stat", false);
    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(i);
    return Service.START_STICKY;
    }//end onStartCommand function


}//end SetupTimerPC1 class

此代码使用广播接收器向不同的类发送一个Boolean值,表示Button是否启动Service 可以被单击(意味着当 Service 启动时,它告诉其他类在服务完成之前不能再次单击 Button。)

这是我用于启动服务的代码:

//start service for timer
startService(new Intent(runGraphics.this, SetupTimerPC1.class));

如果需要更多代码,请告诉我。我真的很感谢你的帮助。谢谢。

最佳答案

您的服务仍在运行。您看到的是设备已 hibernate ,因此计时器不准确。如果您检查设备上的进程列表,即使在退出 Activity 后,您仍然会看到应用的进程正在运行。如果您需要确保您的 Service 在特定的时间间隔(1 分钟、1 小时、1 天或其他)执行某些操作,那么您需要使用 AlarmManager 来确保设备被唤醒,以便您的 Service 可以有时间运行。或者,您可以使用新的 JobScheduler,但它仅限于 Android 5.0+。

关于java - 服务在应用程序关闭时停止,而以前没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27794040/

相关文章:

java - 当抛出未经检查的异常时,异常处理程序是否有办法输出参数?

java - 将数据添加到 JTable 部分代码,转换问题

java - 无法将 Integer 更改为 Double,这会导致我的代码失败

java - Android Studio 监听器导致错误

android - 如何将pdf文件转换为android中的doc文件?

java - 如何与Service层操作JDBC连接

c# - 从服务在事件用户 session 中启动程序?

java - Firebase 实时数据库在查询之间按单词搜索?

android - 如何使用 SherlockListFragment 启动有 Intent 的新 Activity ?

android - 在后台服务中创建地理围栏