如何使用Scheduler进行Http请求

时间:2013-08-30 09:43:12

标签: android android-intent android-notifications

我想在Android中创建一个应用程序,一旦它安装在deive中。它每5分钟发送一次HTTP rrequest。获得响应后它会显示通知。我怎么能这样做。

活动代码

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 for Suggestion。我做了这个:

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

2 个答案:

答案 0 :(得分: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()输入了mili秒。

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

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

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

sendHttpRequestThread.stopSendingHttpRequest();

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

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

答案 1 :(得分:0)

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