"Application is not responding. Would you like to close it?" 在 Android 中 运行 服务时出现错误

"Application is not responding. Would you like to close it?" getting an error while running service in Android

我有一个 Android 应用程序,它有一个启动服务的按钮。

这是服务:

public class SimpleService extends Service 
{
    @Override
    public int onStartCommand(Intent intent,int flags, int startId) 
    {
        Toast.makeText(this,"Service Started",Toast.LENGTH_SHORT).show();               
        Integer i=0;
        while (i<10)
        {
            Log.d("Hi",i.toString());   
            SystemClock.sleep(5000);                    
            i++;            
        }
        Log.d("Hi","return START_STICKY");      
        return START_STICKY;
    }

    public void onDestroy() 
    {       
        super.onDestroy();
        Toast.makeText(this,"Service Stopped",Toast.LENGTH_SHORT).show();           

    }
}

当我点击按钮时,服务启动成功,但过了一段时间,在模拟器中,我收到类似

的错误

Application is not responding. Would you like to close it?

我在服务实施中做错了什么吗?

我想做的是每 5 秒执行一次任务,即使我的应用程序被杀死也是如此。

我尝试使用 IntentService,但当我的应用被终止时它也被终止,所以我的任务仍然未完成。

     while (i<10)
    {
        Log.d("Hi",i.toString());   
        SystemClock.sleep(5000);                    
        i++;            
    }

我想指出你的这部分代码。在这里,您正在做的是一旦您的服务启动,您将进行 10 次循环迭代,并且在每次迭代中您暂停执行 5 秒(就执行而言,这是很多时间)。作为主进程中的服务 运行,在我看来,它们会阻塞主线程,这意味着在睡眠期间,如果访问您的应用程序,您将收到 ANR(应用程序未响应)错误。因此,这些类型的任务应该 运行 在单独的线程中。

如果你想在后台执行一些重复的任务,我建议你使用Android的一个AlarmManager组件 SDK.Alarm管理器是一个系统服务,因此你可以访问它通过使用下面的代码行。

    AlarmManager mAlarmMgr=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
//Then you can set alarm using mAlarmMgr.set().

然后您将在 AlarmReceiver 中收到警报。

AlarmReciever class extends BroadcastReceiver and overrides onRecieve() method. inside onReceive() you can start an activity or service depending on your need like you can start an activity to vibrate phone or to ring the phone.

希望对您有所帮助。干杯!

因为默认情况下,您的所有应用程序组件(如 Activity、服务等)都在 Main/UI 线程中运行,如果它被阻止,Android 会显示 ANR 对话框。

此外,服务的每个生命周期方法都是从 UI 线程调用的。如果您需要后台任务一直 运行,您可以为此创建新线程。

您可以在服务中尝试以下代码 class:

new Thread(new Runnable(){
    public void run() {

    while(i<10)
    {
       Thread.sleep(5000) 
       //REST OF CODE HERE//
    }

 }
}).start();