2013-08-30 1 views
1

deive에 설치되면 Android에서 응용 프로그램을 만들고 싶습니다. 5 분마다 HTTP 요청을 보냅니다. 응답을 얻은 후 알림을 보여줍니다. 어떻게 할 수 있습니까? 이 .스케줄러를 HTTP 요청에 사용하는 방법

활동 코드 지금은 매 5 분에이를 호출하고이 감사 제안에 대한 .I이 가지고 @chintan 저에게이

편집을 도와 notification.Please 보여줄 수있는 방법을

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

    } 
} 

완료 :

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

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 루프를 넣을 필요가있다. 여기서 delayMillis5000을 유지하는 정수 값이며 sleep()은 밀리 초 단위로 입력됩니다.

이것을 실행하려면 Thread 다음 코드를 작성하십시오.

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

Thread을 중지하려면 다음 코드를 작성하십시오.

sendHttpRequestThread.stopSendingHttpRequest(); 

활동이 중지되었을 때이 스레드를 중지하려면 다음과 같이 작성하십시오.

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

에서 메서드 refresh()가 정의되어 있지 않습니다. 여기서 postHttpRequest()를 호출하여 더 설명하지 못합니다. 하나 매 5 분마다 http 요청을 보내야하고 요청에 대한 응답을받은 후 응답해야합니다. –

+0

@Rahul, 내 대답을 편집했습니다. 검토하시기 바랍니다. –

+0

업데이트 한 번 확인하고 문제가 –

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

refresh() 이것은 무엇입니까 ?? –

+0

새로 고침 타이머 클래스 개체 – venu

+0

이것은 표시되는 오류입니다. 새 메서드 TimerTask() {} –

관련 문제