Android在后台工作

时间:2016-01-14 12:26:58

标签: java android

我有3项活动(ABC)以及我打电话检查是否收到来自数据库的新消息的服务。这是一个HTTP请求。我需要每15秒发出一次请求。

 Thread t = new Thread() {

            @Override
            public void run() {
                try {
                    while (!isInterrupted()) {
                        Thread.sleep(15000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                // Here i call                               
                            }
                        });
                    }
                } catch (InterruptedException e) {
                }
            }
        };

        t.start();

当我改变活动时如何使它工作?

2 个答案:

答案 0 :(得分:0)

选项:考虑更改设置以将三个片段作为原始活动,并使用MainActivity控制对DB的消息的重复轮询,以及控制片段。

答案 1 :(得分:0)

@SuppressLint("SimpleDateFormat")
public class AlarmService extends Service {

    private PendingIntent pendingIntent;
    Handler mHandler;
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    @Override
    public void onCreate() {
    }

    public void f() {
        Toast t = Toast.makeText(this, "Service is still running",
                Toast.LENGTH_SHORT);
        t.show();
  };
}
    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        Toast t = Toast.makeText(this, "Service started", Toast.LENGTH_SHORT);
        t.show();

        // TODO Auto-generated method stub
        super.onStart(intent, startId);

        mHandler = new Handler();
        Runnable r = new Runnable() {
            @Override
            public void run() {
                f();
                mHandler.postDelayed(this, 20000);
            }
        };
        mHandler.postDelayed(r, 20000);

    }

}

并在清单中使用此

<service android:name="com.example.yourservice"></service>