【问题标题】:How to use Scheduler for Http Request如何使用调度程序进行 Http 请求
【发布时间】:2013-08-30 09:43:11
【问题描述】:

我想在 Android 中创建一个应用程序,一旦它安装在 deive 中。它每 5 分钟发送一个 HTTP 请求。收到响应后它会显示通知。我该怎么做。

活动代码

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);

    }
}

现在我怎么能每 5 分钟调用一次并显示通知。请帮帮我

编辑 感谢@chintan 的建议。我已经这样做了:

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);
            }
        }
    }
}

【问题讨论】:

    标签: android android-intent android-notifications


    【解决方案1】:

    我创建了一个自定义线程类,它将休眠 5 秒。

    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);
            }
        }
    }
    

    我没有实现所有代码,你需要放入while循环。这里delayMillis 是保持5000 的整数值,因为sleep() 需要输入毫秒。

    要执行此Thread,请编写以下代码。

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

    要停止此Thread,请编写以下代码。

    sendHttpRequestThread.stopSendingHttpRequest();
    

    如果你想在活动停止时停止这个线程,那么写如下。

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

    【讨论】:

    • 从哪里我会调用我的 postHttpRequest () 我没有得到请解释一下。每 5 分钟我必须发送一次 http 请求,并在收到请求的响应后通知它跨度>
    • 更新了我的代码会检查一次,如果有问题就更新。谢谢
    • @Rahul,我在线程中使用了sendHttpRequestautoNotify()。这不会检查您的回复。正如你已经检查了你的方法。所以我要从线程中删除autoNotify 的代码。这将保留在您的 http 方法中。当有响应码 200 时,会通知您。 :)
    • 任何 UI 部件,例如一旦安装就不想显示任何类型的 UI @chitan 我想和你讨论 ..我需要你的建议......并且你的代码现在可以正常工作了非常感谢
    【解决方案2】:

    在 onCreate() 方法中替换下面的代码

    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);
    

    【讨论】:

    • 刷新()这是什么??
    • 刷新是定时器类对象
    • 这是它所显示的错误。新 TimerTask(){} 类型的方法 refresh() 未定义
    猜你喜欢
    • 1970-01-01
    • 2021-06-27
    • 2019-02-28
    • 2011-08-30
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多