Example usage for android.os Handler Handler

List of usage examples for android.os Handler Handler

Introduction

In this page you can find the example usage for android.os Handler Handler.

Prototype

public Handler() 

Source Link

Document

Default constructor associates this handler with the Looper for the current thread.

Usage

From source file:me.tassoevan.cordova.ForegroundService.java

@Override
public void onCreate() {
    super.onCreate();

    final Handler handler = new Handler();

    startForeground(NOTIFICATION_ID, makeNotification());

    keepAliveTask = new TimerTask() {
        @Override/*www  . ja va  2 s  . c o m*/
        public void run() {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d(BackgroundPlugin.class.getName(), "" + new Date().getTime());
                }
            });
        }
    };

    scheduler.schedule(keepAliveTask, 0, 1000);
}

From source file:com.tealeaf.AppFinder.java

public AppFinder(final TestAppActivity activity, Context context, final String host, final int port) {
    WifiManager wifi = (WifiManager) context.getSystemService(android.content.Context.WIFI_SERVICE);
    lock = wifi.createMulticastLock("tealeaflock");
    lock.setReferenceCounted(true);//from w ww .j  a v a  2 s.c  o  m
    lock.acquire();

    handler = new Handler();
    // don't block the main thread
    // search /projects of the given host:port for manifests
    new Thread(new Runnable() {
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    activity.showAppLoadingDialog();
                }
            });

            ArrayList<AppInfo> appInfos = new ArrayList<AppInfo>();
            String url = "http://" + host + ":" + port + "/projects";
            HTTP http = new HTTP();
            logger.log("GETTING BODY", url);
            String body = http.get(URI.create(url));
            logger.log("BODY", body);

            try {
                JSONObject json = new JSONObject(body);
                JSONArray jsonNames = json.names();
                //loop through and add to list
                for (int i = 0; i < jsonNames.length(); i++) {

                    try {
                        String projectName = jsonNames.get(i).toString();
                        JSONObject curObj = json.getJSONObject(projectName);
                        boolean isExample = false;
                        //id is used for serving
                        if (!curObj.has("id"))
                            continue;
                        String id = (String) curObj.get("id");
                        if (!curObj.has("manifest"))
                            continue;
                        JSONObject manifest = curObj.getJSONObject("manifest");
                        if (!manifest.has("title"))
                            continue;
                        String title = (String) manifest.get("title");
                        if (!manifest.has("appID"))
                            continue;
                        String appid = (String) manifest.get("appID");
                        if (manifest.has("group")) {
                            String group = (String) manifest.get("group");
                            isExample = group.equals("examples");
                        }
                        //try and fail gracefully if no icons exist, use default
                        JSONObject androidObj = manifest.getJSONObject("android");
                        JSONObject icons = androidObj.has("icons") ? androidObj.getJSONObject("icons")
                                : new JSONObject();
                        JSONArray iconNames = null;
                        int iconIndex = 0;
                        if (icons.names() != null) {
                            iconNames = icons.names();
                            //hopefully get the url for the largest icon
                            int lastNum = 0;
                            for (int j = 0; j < iconNames.length(); j++) {
                                try {
                                    int num = Integer.parseInt(iconNames.get(j).toString());
                                    if (num > lastNum) {
                                        lastNum = num;
                                        iconIndex = j;
                                    }
                                } catch (Exception e) {
                                    //some number can't parse exception
                                    logger.log(e);
                                }
                            }
                        }
                        String iconURL = "default";
                        if (icons.names() != null) {
                            iconURL = (String) icons.get(iconNames.get(iconIndex).toString());
                        }
                        if (!manifest.has("supportedOrientations"))
                            continue;
                        String orientation = (String) ((JSONArray) manifest
                                .getJSONArray("supportedOrientations")).get(0);
                        boolean isPortrait = orientation.equalsIgnoreCase("portrait");
                        AppInfo app = new AppInfo(title, appid, isPortrait, id, iconURL);
                        app.isExample = isExample;
                        appInfos.add(app);
                    } catch (Exception e) {
                        logger.log(e);
                        continue;
                    }

                }
            } catch (Exception e) {
                logger.log(e);
            }
            handler.post(new Runnable() {
                public void run() {
                    activity.dismissAppLoadingDialog();
                }
            });
            Collections.sort(appInfos, new Comparator<AppInfo>() {
                @Override
                public int compare(AppInfo lhs, AppInfo rhs) {
                    //If the apps are in the same category compare by name
                    if (lhs.isExample == rhs.isExample) {
                        return lhs.name.compareTo(rhs.name);
                    }
                    //otherwise an example app is considered "greater" than
                    //a non example app and is moved to the bottom of the list
                    return lhs.isExample ? 1 : -1;
                }

            });
            createAdapter(activity, appInfos, host, port);
        }
    }).start();
}

From source file:com.dedipower.portal.android.InvoiceLanding.java

public void onCreate(Bundle savedInstanceState) {
    API.SessionID = getIntent().getStringExtra("sessionid");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.invoicelanding);
    final ListView list = (ListView) findViewById(R.id.InvoiceList);

    final ProgressDialog dialog = ProgressDialog.show(this, "DediPortal", "Please wait: loading data....",
            true);//from   w  ww  . ja  v  a 2  s. c  o  m
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();
            if (Success.equals("true")) {
                UpdateErrorMessage(ErrorMessage);
                InvoiceAdaptor adapter = new InvoiceAdaptor(InvoiceLanding.this, listOfInvoices, API.SessionID);
                list.setAdapter(adapter);
            } else {
                UpdateErrorMessage(ErrorMessage);
            }
        }
    };

    Thread dataPreload = new Thread() {
        public void run() {
            try {
                InvoiceAPIReturn = API.PortalQueryHack("invoices", "", "");
                Success = InvoiceAPIReturn.getString("success");
            } catch (JSONException e) {
                ErrorMessage = "An unrecoverable JSON Exception occured.";
                Success = "false";
            }

            if (Success.equals("false")) {
                Log.i("API", "Success was false");
                try {
                    ErrorMessage = InvoiceAPIReturn.getJSONObject("hackReturn").getString("msg");
                } catch (JSONException e) {
                    ErrorMessage = "A JSON parsing error prevented an exact error message to be determined.";
                }
            } else {
                int InvoiceCount = 0;
                Log.i("APIFuncs", InvoiceAPIReturn.toString());
                try {
                    Invoices = InvoiceAPIReturn.getJSONObject("hackReturn").getJSONArray("data");
                    InvoiceCount = Invoices.length();
                    ErrorMessage = "";
                } catch (JSONException e) {
                    ErrorMessage = "There don't appear to be any invoices for your account.....";
                    InvoiceCount = 0;
                    Log.e("API", "There was an eror parsing the array");
                    Log.e("API", e.getMessage());
                }

                //OK lets actually do something useful

                if (InvoiceCount == 0) {
                    Success = "false";
                    ErrorMessage = "There are no invoices for your account.";
                    handler.sendEmptyMessage(0);
                    return;
                }

                for (int i = 0; i < InvoiceCount; i++) {
                    JSONObject CurrentInvoice = null;
                    try {
                        CurrentInvoice = Invoices.getJSONObject(i);
                    } catch (JSONException e1) {
                        Log.e("APIFuncs", e1.getMessage());
                    }
                    try {
                        if (CurrentInvoice.getString("type").equals("invoice"))
                            listOfInvoices.add(new Invoices(CurrentInvoice.getString("ref"),
                                    CurrentInvoice.getDouble("amount"), CurrentInvoice.getString("details"),
                                    CurrentInvoice.getLong("date")));
                    } catch (JSONException e) {
                        Log.e("APIFuncs", e.getMessage());
                    }
                }
            }

            handler.sendEmptyMessage(0);
        }
    };

    dataPreload.start();
}

From source file:com.dedipower.portal.android.TicketLanding.java

public void onCreate(Bundle savedInstanceState) {
    API.SessionID = getIntent().getStringExtra("sessionid");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ticketlanding);
    final ListView list = (ListView) findViewById(R.id.TicketList);

    final ProgressDialog dialog = ProgressDialog.show(this, "DediPortal", "Please wait: loading data....",
            true);/*w  w  w.  j  a v  a2s  . com*/
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();
            if (Success.equals("true")) {
                UpdateErrorMessage(ErrorMessage);
                OpenTicketsAdaptor adapter = new OpenTicketsAdaptor(TicketLanding.this, listOfTickets,
                        API.SessionID);
                list.setAdapter(adapter);
            } else {
                UpdateErrorMessage(ErrorMessage);
            }
        }
    };

    Thread dataPreload = new Thread() {
        public void run() {
            try {
                TicketAPI = API.PortalQuery("tickets", "none");
                Success = TicketAPI.getString("success");
            } catch (JSONException e) {
                ErrorMessage = "An unrecoverable JSON Exception occured.";
                Success = "false";
            }

            if (Success.equals("false")) {
                try {
                    ErrorMessage = TicketAPI.getString("msg");
                } catch (JSONException e) {
                    ErrorMessage = "A JSON parsing error prevented an exact error message to be determined.";
                }
            } else {
                Log.i("APIFuncs", TicketAPI.toString());
                try {
                    Tickets = TicketAPI.getJSONArray("tickets");
                    ErrorMessage = "";
                } catch (JSONException e) {
                    ErrorMessage = "There are no open tickets for your account.";
                }

                //OK lets actually do something useful
                //ListView list = (ListView)findViewById(R.id.TicketList);
                //List<OpenTickets> listOfTickets = new ArrayList<OpenTickets>();
                int TicketCount = Tickets.length();

                if (TicketCount == 0) {
                    ErrorMessage = "There are no open tickets for your account.";
                    handler.sendEmptyMessage(0);
                    return;
                }

                for (int i = 0; i < TicketCount; i++) {
                    JSONObject CurrentTicket = null;
                    try {
                        CurrentTicket = Tickets.getJSONObject(i);
                    } catch (JSONException e1) {
                        Log.e("APIFuncs", e1.getMessage());
                    }
                    try {
                        listOfTickets.add(new OpenTickets(CurrentTicket.getString("status"),
                                CurrentTicket.getInt("id"), CurrentTicket.getString("server"),
                                CurrentTicket.getString("email"), CurrentTicket.getString("subject"),
                                CurrentTicket.getInt("createdat"), CurrentTicket.getInt("lastupdate"), false));
                        //CurrentTicket.getBoolean("subscriber")));
                    } catch (JSONException e) {
                        Log.e("APIFuncs", e.getMessage());
                    }
                }
            }

            handler.sendEmptyMessage(0);
        }
    };

    dataPreload.start();
}

From source file:org.casquesrouges.missing.HttpAdapter.java

public HttpAdapter() {
    this(new Handler(), null);
}

From source file:com.lurencun.cfuture09.androidkit.http.async.AsyncHttpResponseHandler.java

public AsyncHttpResponseHandler() {
    // handler???
    if (Looper.myLooper() != null) {
        handler = new Handler() {
            @Override//from  w  w w.  ja  va  2s.  c o m
            public void handleMessage(Message msg) {
                AsyncHttpResponseHandler.this.handleMessage(msg);
            }
        };
    }
}

From source file:com.simpleminds.popbell.Doc_Parsing.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.doclayout);/*from  w  w  w .ja  v a 2 s  . c o m*/
    intent = getIntent();
    getSupportActionBar().setTitle(intent.getExtras().getString("Data"));
    helloTxt = (TextView) findViewById(R.id.contents);
    handler = new Handler();
    new Thread(runnable).start();
}

From source file:co.uk.rehope.androidapp.DrawableManager.java

public void fetchDrawableOnThread(final String urlString, final ImageView imageView) {
    if (drawableMap.containsKey(urlString)) {
        imageView.setImageDrawable((Drawable) drawableMap.get(urlString));
    }//from   w  ww .j  a v a 2s.c  o  m

    final Handler handler = new Handler() {
        public void handleMessage(Message message) {
            imageView.setImageDrawable((Drawable) message.obj);
        }
    };

    Thread thread = new Thread() {
        @Override
        public void run() {
            // TODO : set imageView to a "pending" image
            Drawable drawable = fetchDrawable(urlString);
            Message message = handler.obtainMessage(1, drawable);
            handler.sendMessage(message);
        }
    };
    thread.start();
}

From source file:com.miuidev.themebrowser.MainActivity.java

/** Called when the activity is first created. */
@Override//from   w ww .  ja va 2s  . c  om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tab);

    mHandler = new Handler();
    checkUpdate.start();

    TabHost tabHost = getTabHost();
    TabHost.TabSpec spec;
    Intent intent;

    intent = new Intent().setClass(this, FeaturedThemesActivity.class);
    spec = tabHost.newTabSpec("featuredthemes").setIndicator(getString(R.string.tab_featured_themes))
            .setContent(intent);
    tabHost.addTab(spec);

    intent = new Intent().setClass(this, AllThemesActivity.class);
    spec = tabHost.newTabSpec("allthemes").setIndicator(getString(R.string.tab_all_themes)).setContent(intent);
    tabHost.addTab(spec);

}

From source file:cn.newgxu.android.notty.service.FetchService.java

@Override
public void onCreate() {
    super.onCreate();
    handler = new Handler();
}