1

我想在 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);
            }
        }
    }
}
4

2 回答 2

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();
}
于 2013-08-30T10:36:57.273 回答
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);
于 2013-08-30T10:04:04.553 回答