【问题标题】:Running process also if the app is closed如果应用程序关闭,也会运行进程
【发布时间】:2014-03-03 14:07:42
【问题描述】:

我正在制作一个应用程序,它需要每隔 10 秒检查一次文件是否存在。如果文件中写有“SEND”,则发送消息,否则不执行任何操作。 如果有文件,我怎么能创建一个线程/进程每 10 秒检查一次,即使我关闭了应用程序?是否可以? 这是我的代码:

public class BootListener extends BroadcastReceiver {
    public BootListener() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context, FileCheckerService.class));
    }
}


public class FileCheckerService extends Service {
    public FileCheckerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                SmsManager newSms = SmsManager.getDefault();
                newSms.sendTextMessage(
                        "+39334659348",
                        null,
                        "TRY",
                        null,
                        null);
            }
        };

        Timer timer = new Timer();
        timer.schedule(task, 0, 20000);

        return START_STICKY;
    }

    public static String convertStreamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        reader.close();
        return sb.toString();
    }
}

【问题讨论】:

    标签: android multithreading process


    【解决方案1】:

    尝试使用服务。阅读更多关于正确使用服务的方法:

    http://developer.android.com/reference/android/app/Service.html

    【讨论】:

      【解决方案2】:

      创建一个具有应用程序上下文的服务,其中覆盖startCommand 返回Service.start_sticky 标志,并在其中设置while循环的一侧有线程,如下所示

      while(true)
       {
          yourThreadReference.sleep(10000); // this is 10 seconds
          // do your work  
       } 
      

      【讨论】:

      • 我试过了,只要应用程序还活着,它就可以工作。一旦我关闭应用程序,它就会停止发送短信..
      • 我认为您使用的是活动上下文而不是应用程序上下文。使用 android manifest.xml 进行广播注册
      • 对不起,我看不懂,你能做一个示例代码吗?为什么要使用广播接收器?
      • 一旦启动完成,您需要捕获启动意图,因此需要它,同时运行线程将负责服务始终运行,因此应用程序进程也将正在运行
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 1970-01-01
      • 2023-01-26
      • 2012-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多