How to use Scheduler for Http Request

爱⌒轻易说出口 提交于 2019-12-11 04:54:15

问题


I want to create a application in Android that once it is installed in the deive.It send a HTTP rrequest in every 5 mins .After getting the response it shows the notification .How could i do this .

Activity Code

public class AutoNotification extends Activity {
    String url="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto_notification);
        postHttpRequest("Test","Test");

    }

    public  void postHttpRequest(String userId,String pass){
        RequestClient reqClient = new RequestClient(AutoNotification.this);
        String AppResponse = null;
        try {
            url = "";
            Log.d("URL", url);
            AppResponse = reqClient.execute().get();
            String status = "200";
            Log.d("Status recived", status);

            if(status.equals("200")){
                autoNotify();
            }
        } catch (Exception e) {
            Log.e("Exception Occured", "Exception is "+e.getMessage());
        }
    }
    public void autoNotify(){
        Intent intent = new Intent();
        PendingIntent pIntent = PendingIntent.getActivity(AutoNotification.this, 0, intent, 0);
        Builder builder = new NotificationCompat.Builder(getApplicationContext())
            .setTicker("Test Title").setContentTitle("Content Test")
            .setContentText("Test Notification.")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent);
        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(notificationSound);
        Notification noti = builder.build();    
        noti.flags = Notification.FLAG_AUTO_CANCEL;
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, noti);

    }
}

Now how could i call this on every 5 min and show the notification.Please help me this

Edit Thanks @chintan for Suggestion .i have done this :

public class AutoNotification extends Activity {
    String url="";
    private Timer refresh = null;
    private final long refreshDelay = 5 * 1000;
    SendHttpRequestThread sendHttpRequestThread; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto_notification);

        sendHttpRequestThread = new SendHttpRequestThread("Test","Test");
        sendHttpRequestThread.start();

    }



    public  void postHttpRequest(String userId,String pass){
        RequestClient reqClient = new RequestClient(AutoNotification.this);
        String AppResponse = null;
        try {
            url = "";
            Log.d("URL", url);
            AppResponse = reqClient.execute(url).get();
            String status = "200";
            Log.d("Status recived", status);

            if(status.equals("200")){
                autoNotify();
            }
        } catch (Exception e) {
            Log.e("Exception Occured", "Exception is "+e.getMessage());
        }
    }
    public void autoNotify(){
        Intent intent = new Intent();
        PendingIntent pIntent = PendingIntent.getActivity(AutoNotification.this, 0, intent, 0);
        Builder builder = new NotificationCompat.Builder(getApplicationContext())
            .setTicker("Test Title").setContentTitle("Content Test")
            .setContentText("Test Notification.")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent);
        Uri notificationSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(notificationSound);
        Notification noti = builder.build();    
        noti.flags = Notification.FLAG_AUTO_CANCEL;
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(0, noti);

    }

    class SendHttpRequestThread extends Thread {

        boolean sendHttpRequest;
        String userId;
        String pass;

        public SendHttpRequestThread(String str1, String str2) {
            this.userId = str1;
            this.pass = str2;
            sendHttpRequest = true;
        }

        public void stopSendingHttpRequest() {
            sendHttpRequest = false;
        }

        protected void onStop() {
            sendHttpRequestThread.stopSendingHttpRequest();
            super.stop();
        }

        @Override
        public void run() {
            while (sendHttpRequest) {
                postHttpRequest(userId, pass);

                SystemClock.sleep(refreshDelay);
            }
        }
    }
}

回答1:


I created one Custom Thread class which will sleep for 5 secs.

public class SendHttpRequestThread extends Thread {

    boolean sendHttpRequest;
    String userId;
    String pass;

    public SendHttpRequestThread(String str1, String str2) {
        this.userId = str1;
        this.pass = str2;
        sendHttpRequest = true;
    }

    public void stopSendingHttpRequest() {
        sendHttpRequest = false;
    }

    @Override
    public void run() {
        while (sendHttpRequest) {
            postRequest(userId, pass);
            //add code here to execute in background thread
            autoNotify();
            SystemClock.sleep(delayMillis);
        }
    }
}

I didn't implemented all code, you need to put inside while loop. Here delayMillis is integer value holding 5000 as sleep() takes input of mili seconds.

To execute this Thread, write following code.

sendHttpRequestThread = new SendHttpRequestThread("Test","Test");
sendHttpRequestThread.start();

To stop this Thread, write following code.

sendHttpRequestThread.stopSendingHttpRequest();

If you want to stop this thread when activity is stopped, then write like below.

@Override
protected void onStop() {
    sendHttpRequestThread.stopSendingHttpRequest();
    super.onStop();
}



回答2:


Replace below code in onCreate() method

private Timer refresh = null;
    private final long refreshDelay = 5 * 1000;

            if (refresh == null) { // start the refresh timer if it is null
                refresh = new Timer(false);

                Date date = new Date(System.currentTimeMillis()+ refreshDelay);
                refresh.schedule(new TimerTask() {

                        @Override
                        public void run() {
                             postHttpRequest("Test","Test");
                            refresh();
                        }
                    }, date, refreshDelay);


来源:https://stackoverflow.com/questions/18529802/how-to-use-scheduler-for-http-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!