如何更改 Activity 当服务器中的标志更改时,应用应每 30 秒检查一次服务器 #android?

How to Change Activity When flag in server changes,so app should check server once in every 30 seconds #android?

你好我正在做一个项目,在那个项目中我遇到了一个挑战,它是一个简单的社区新闻应用程序,所以当用户每 30 秒打开该应用程序时,该应用程序的后台服务应该检查标志服务器,以便根据该标志 activity 应该更改,当应用程序关闭时我怎样才能实现这一点,后台任务必须被终止。

您可以使用 Executer Service,它将 运行 直到您的应用程序处于活动状态。

private var exec: ScheduledThreadPoolExecutor? = null
private var pollTask: ScheduledFuture<*>? = null

private fun schedulePollTask() {
        pollTask = getScheduler().scheduleWithFixedDelay(PollTask(), INITIAL_DELAY, getTaskIntervalDuration(), TimeUnit.SECONDS)
    }

private fun getScheduler():ScheduledThreadPoolExecutor {
        if (exec == null) {
            exec = ScheduledThreadPoolExecutor(1)
            exec?.executeExistingDelayedTasksAfterShutdownPolicy = false
        }
        return exec!!
    }

internal inner class PollTask : Runnable {

        override fun run() {
            hitApi()
            try{
                if (timeInterval <= 0) {
                    timeInterval = 15
                }
                Thread.sleep(timeInterval * 1000)
            }catch (e: InterruptedException){
                // task completed
            }
        }
    }

我使用了带有后台服务的自定义广播接收器,这里后台服务每 10 秒检查一次标志,如果更改标志,它将触发自定义广播接收器

FlagCheckerServce.java:-

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class FlagCheckerServce extends Service {
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 10000;
    HttpURLConnection conn;
    URL url = null;
    int current=0;
    int flag=0;
    private Handler mHandler;
    public static final long DEFAULT_SYNC_INTERVAL = 10 * 1000;
    public FlagCheckerServce() {
    }
    @Override
    public IBinder onBind(Intent intent) {
        return  null;
    }
    private Runnable runnableService = new Runnable() {
        @Override
        public void run() {
            syncData();
            mHandler.postDelayed(runnableService,DEFAULT_SYNC_INTERVAL);
        }
    };
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mHandler = new Handler();
        mHandler.post(runnableService);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
    }

    private synchronized void syncData() {

        new AsyncFetch1().execute();
        /*

        #####data base value of i

        manupulate flag value
         */

        if(flag!=current){
            if(flag==0){
                current=0;
                Intent i1=new Intent();
                i1.setAction("com.MainMenu");
                i1.addCategory("android.intent.category.DEFAULT");
                sendBroadcast(i1);

            }
            if(flag==1){
                current=1;
                Intent i1=new Intent();
                i1.setAction("com.Quiz");
                i1.addCategory("android.intent.category.DEFAULT");
                sendBroadcast(i1);

            }
            if(flag==2){
                current=2;
                Intent i1=new Intent();
                i1.setAction("com.ImageQuiz");
                i1.addCategory("android.intent.category.DEFAULT");
                sendBroadcast(i1);

            }
            if(flag==3){
                current=3;
                Intent i1=new Intent();
                i1.setAction("com.QR");
                i1.addCategory("android.intent.category.DEFAULT");
                sendBroadcast(i1);

            }
            if(flag==4){
                current=4;
                Intent i1=new Intent();
                i1.setAction("com.BestPic");
                i1.addCategory("android.intent.category.DEFAULT");
                sendBroadcast(i1);
            }


        }



    }

    private class AsyncFetch1 extends AsyncTask<String, String, String> {
        public static final int CONNECTION_TIMEOUT = 10000;
        public static final int READ_TIMEOUT = 15000;
        HttpURLConnection conn;
        URL url = null;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        protected String doInBackground(String... params) {
            try {
                url = new URL("http://accoladetest.cf/MyApi/MyApiFlagCheck.php");
            } catch (MalformedURLException e) {
                e.printStackTrace();
                return  e.toString();
            }
            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");
                conn.setDoOutput(true);
            } catch (IOException e1) {
                e1.printStackTrace();
                return  e1.toString();
            }
            try {
                int response_code = conn.getResponseCode();
                if (response_code == HttpURLConnection.HTTP_OK) {

                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }
                    return (result.toString());
                } else {
                    return "Buffer Error";
                }
            } catch (IOException e) {
                e.printStackTrace();
                return  e.toString();
            } finally {
                conn.disconnect();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            try {
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);

                    flag= json_data.getInt("flag");
                    if(flag!=current){
                        if(flag==0){
                            current=0;
                            Intent i1=new Intent();
                            i1.setAction("com.MainMenu");
                            i1.addCategory("android.intent.category.DEFAULT");
                            sendBroadcast(i1);

                        }
                        if(flag==1){
                            current=1;
                            Intent i1=new Intent();
                            i1.setAction("com.Quiz");
                            i1.addCategory("android.intent.category.DEFAULT");
                            sendBroadcast(i1);

                        }
                        if(flag==2){
                            current=2;
                            Intent i1=new Intent();
                            i1.setAction("com.ImageQuiz");
                            i1.addCategory("android.intent.category.DEFAULT");
                            sendBroadcast(i1);

                        }
                        if(flag==3){
                            current=3;
                            Intent i1=new Intent();
                            i1.setAction("com.QR");
                            i1.addCategory("android.intent.category.DEFAULT");
                            sendBroadcast(i1);

                        }
                        if(flag==4){
                            current=4;
                            Intent i1=new Intent();
                            i1.setAction("com.BestPic");
                            i1.addCategory("android.intent.category.DEFAULT");
                            sendBroadcast(i1);
                        }


                    }



                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }
}

FlagImageQuizBroadcastReceiver.java:-(对于每个 activity 会有不同的广播接收器,我在下面只提到了一个):-

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class FlagImageQuizBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intentImageQuiz=new Intent(context,ImageQuiz.class);
        context.startActivity(intentImageQuiz);
    }
}

在MainActivity.java的onCreate方法中调用启动服务:-

 Intent i3=new Intent(this,FlagCheckerServce.class);
 startService(i3);

使用自定义广播的接收者标签更新清单文件

 <receiver
            android:name=".FlagImageQuizBroadcastReceiver"
            android:enabled="true"
            android:exported="true" >
            <intent-filter>
                <action android:name="com.ImageQuiz"></action>
                <category android:name="android.intent.category.DEFAULT"></category>
            </intent-filter>

  </receiver>