본문 바로가기
forDREAM/Engineering

[App] DaSAS Source

by tothebeyond 2020. 2. 23.
반응형

<MainActivity.java>

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {
    private Button btnStart, btnEnd;
    WebView WV1;
    TextView TV1;
    int Count0 = 0;
    Intent intent2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnStart = (Button)findViewById(R.id.button1);
        btnEnd = (Button)findViewById(R.id.button2);
        WV1 = (WebView) findViewById(R.id.webView);
        WV1.setWebViewClient(new MyWebViewClient());
        TV1 = (TextView) findViewById(R.id.textView);
        TV1.setText("[DaSAS]");

        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.BR");
        registerReceiver(BR, filter);

        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"Service 시작", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this,DSASService.class);
                startService(intent);
            }
        });

        btnEnd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"Service 끝",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(MainActivity.this,DSASService.class);
                stopService(intent);
            }
        });
    }

     public String h_ExecuteScheduledJob(){
        long Now0 = System.currentTimeMillis();
        Calendar Cal0 = Calendar.getInstance();
        Cal0.setTimeInMillis(Now0);
        int Hour0 = Cal0.get(Calendar.HOUR_OF_DAY);
        int Min0 = Cal0.get(Calendar.MINUTE);
         int Sec0 = Cal0.get(Calendar.SECOND);
        String tURL="";
/*         int theNumber = (int)(Math.random()*1000);

         switch(theNumber%3){
             case 0:
                 tURL = "http://www.naver.com";
                 break;
             case 1:
                 tURL = "http://www.daum.net";
                 break;
             case 2:
                 tURL = "http://www.google.com";
                 break;
             default:
                 tURL = "http://www.nate.com";
                 break;
         }
*/        // Defaul URL : http://www.dsaservice.net/
        switch (Hour0) {
            case 7:
                if (Min0 < 30) tURL = "http://www.dsaservice.net/DSAS/Manage/CollectContents201706.html";
                else tURL = "DSAS/Manage/MailingService201706.html";
                break;
            case 13:
                if (Min0 < 30) tURL = "http://www.dsaservice.net/DSAS/Manage/CollectContents201706.html";
                else tURL = "http://www.dsaservice.net/DSAS/Manage/MailingService201706.html";
                break;

            case 8:
            case 9:
            case 10:
            case 11:
            case 12:
            case 14:
            case 15:
            case 16:
            case 17:
            case 18:
            case 19:
            case 20:
                if (Min0 < 30) tURL = "http://www.dsaservice.net/DSAS/Manage/CollectContents201706.html";
                break;
            default:
                tURL = "http://www.google.com";
                break;
        }

        final String mURL = tURL;
         WV1.loadUrl(mURL);
         TV1.setText(TV1.getText()+"/"+Hour0+":"+Min0);

        return mURL;

    }

    BroadcastReceiver BR = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent){
            if(intent.getStringExtra("DSAS_RESPONSE") != null){
                h_ExecuteScheduledJob();
            }
        }
    };

}

class MyWebViewClient extends WebViewClient {

    // 로딩이 시작될 때
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }

    // 리소스를 로드하는 중 여러번 호출
    @Override
    public void onLoadResource(WebView view, String url) {
        super.onLoadResource(view, url);
    }

    // 방문 내역을 히스토리에 업데이트 할 때
    @Override
    public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
        super.doUpdateVisitedHistory(view, url, isReload);
    }

    // 로딩이 완료됬을 때 한번 호출
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
    }

    // 오류가 났을 경우, 오류는 복수할 수 없음
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);

        switch (errorCode) {
            case ERROR_AUTHENTICATION:
                break;               // 서버에서 사용자 인증 실패
            case ERROR_BAD_URL:
                break;                           // 잘못된 URL
            case ERROR_CONNECT:
                break;                          // 서버로 연결 실패
            case ERROR_FAILED_SSL_HANDSHAKE:
                break;    // SSL handshake 수행 실패
            case ERROR_FILE:
                break;                                  // 일반 파일 오류
            case ERROR_FILE_NOT_FOUND:
                break;               // 파일을 찾을 수 없습니다
            case ERROR_HOST_LOOKUP:
                break;           // 서버 또는 프록시 호스트 이름 조회 실패
            case ERROR_IO:
                break;                              // 서버에서 읽거나 서버로 쓰기 실패
            case ERROR_PROXY_AUTHENTICATION:
                break;   // 프록시에서 사용자 인증 실패
            case ERROR_REDIRECT_LOOP:
                break;               // 너무 많은 리디렉션
            case ERROR_TIMEOUT:
                break;                          // 연결 시간 초과
            case ERROR_TOO_MANY_REQUESTS:
                break;     // 페이지 로드중 너무 많은 요청 발생
            case ERROR_UNKNOWN:
                break;                        // 일반 오류
            case ERROR_UNSUPPORTED_AUTH_SCHEME:
                break; // 지원되지 않는 인증 체계
            case ERROR_UNSUPPORTED_SCHEME:
                break;          // URI가 지원되지 않는 방식
        }

    }

    // http 인증 요청이 있는 경우, 기본 동작은 요청 취소
    @Override
    public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
        super.onReceivedHttpAuthRequest(view, handler, host, realm);
    }

    // 확대나 크기 등의 변화가 있는 경우
    @Override
    public void onScaleChanged(WebView view, float oldScale, float newScale) {
        super.onScaleChanged(view, oldScale, newScale);
    }

    // 잘못된 키 입력이 있는 경우
    @Override
    public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
        return super.shouldOverrideKeyEvent(view, event);
    }

    // 새로운 URL이 webview에 로드되려 할 경우 컨트롤을 대신할 기회를 줌
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

 

<DSASService.java>

package com.example.yoon.dsaservice0;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.Gravity;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

public class DSASService extends Service {
    NotificationManager Notifi_M;
    ServiceThread thread;
    Notification Notifi;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Notifi_M = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        myServiceHandler handler = new myServiceHandler();
        thread = new ServiceThread(handler);
        thread.start();
        return START_STICKY;
    }

    //서비스가 종료될 때 할 작업

    public void onDestroy() {
        thread.stopForever();
        thread = null;//쓰레기 값을 만들어서 빠르게 회수하라고 null을 넣어줌.
    }



    class myServiceHandler extends Handler {
        String tStr3;
        @Override
        public void handleMessage(android.os.Message msg) {
            Intent intent = new Intent(DSASService.this, MainActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(DSASService.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            Notifi = new Notification.Builder(getApplicationContext())
                    .setContentTitle("Content Title")
                    .setContentText("Content Text")
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setTicker("알림!!!")
                    .setContentIntent(pendingIntent)
                    .build();

            //소리추가
//            Notifi.defaults = Notification.DEFAULT_SOUND;


            //알림 소리를 한번만 내도록
//            Notifi.flags = Notification.FLAG_ONLY_ALERT_ONCE;

            //확인하면 자동으로 알림이 제거 되도록
            Notifi.flags = Notification.FLAG_AUTO_CANCEL;


            Notifi_M.notify(777, Notifi);

            tStr3="/";
            Intent intent2 = new Intent();
            intent2.setAction("com.example.BR");
            intent2.putExtra("DSAS_RESPONSE",tStr3);
            sendBroadcast(intent2);

            //토스트 띄우기
            Toast.makeText(DSASService.this, "[DaSAS]"+tStr3, Toast.LENGTH_LONG).show();
        }
    };

}

 

'forDREAM > Engineering' 카테고리의 다른 글

Technology Evangelist<LG-ERI>, 2014.10.28  (1) 2020.02.25
Kickstarter > Technology, 2020.02.23  (1) 2020.02.23
PHP를 이용한 Web-crawling  (0) 2020.02.22
[Python] 내장함수  (0) 2020.02.21
홀로렌즈(Microsoft) 사례, 2015.08.19  (0) 2020.02.20