Example usage for android.os Looper prepare

List of usage examples for android.os Looper prepare

Introduction

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

Prototype

public static void prepare() 

Source Link

Document

Initialize the current thread as a looper.

Usage

From source file:eu.dirtyharry.androidopsiadmin.Main.java

public void getOPSIDepotConfig(final String depot) {
    final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait),
            String.format(getString(R.string.pd_getdepotconfigfor), depot), true);
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();/*from ww w.  j av  a 2s  .  co  m*/
            if (GlobalVar.getInstance().getError().equals("null")) {
                Intent i = new Intent(Main.this, ShowOpsiHostParamsListView.class);
                Bundle b = new Bundle();
                b.putString("hostparams", opsiresult.toString());
                b.putString("pc", choosendepot);
                b.putString("opsitype", "OpsiConfigserver");
                i.putExtras(b);
                startActivityForResult(i, SHOW_OPSI_DEPOT_REQUEST);
            } else {
                new Functions().msgBox(Main.this, getString(R.string.gen_title_error),
                        GlobalVar.getInstance().getError(), false);
            }

        }
    };
    Thread checkUpdate = new Thread() {
        public void run() {
            Looper.prepare();
            JSONArray JSONparams = new JSONArray();
            JSONparams.put(depot);
            opsiresult = new JSONObject();
            opsiresult = eu.dirtyharry.androidopsiadmin.Networking.opsiGetJSONObject("rpc", serverip,
                    serverport, "getDepot_hash", JSONparams, serverusername, serverpasswd);
            handler.sendEmptyMessage(0);
        }
    };
    checkUpdate.start();
}

From source file:com.klinker.android.twitter.activities.tweet_viewer.TweetPager.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();//from  w  w  w  .j  a  v  a 2 s .  c o m
        return true;

    case R.id.menu_delete_tweet:
        new DeleteTweet().execute();
        getSharedPreferences("com.klinker.android.twitter_world_preferences", 0).edit()
                .putBoolean("just_muted", true).commit();
        return true;

    case R.id.menu_share:
        String text1 = tweet;
        text1 = "@" + screenName + ": " + text1 + "\n\n" + "https://twitter.com/" + screenName + "/status/"
                + tweetId;
        Log.v("my_text_on_share", text1);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("text/plain");
        share.putExtra(Intent.EXTRA_TEXT, text1);

        startActivity(share);
        return true;

    case R.id.menu_copy_text:
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("tweet_text", tweet);
        clipboard.setPrimaryClip(clip);
        return true;

    /*case R.id.menu_open_web:
        Uri weburi;
        try {
            weburi = Uri.parse(otherLinks[0]);
        } catch (Exception e) {
            weburi = Uri.parse(webpage);
        }
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, weburi);
        startActivity(launchBrowser);
            
        return true;*/

    case R.id.menu_save_image:

        new Thread(new Runnable() {
            @Override
            public void run() {

                Looper.prepare();

                try {
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.downloading) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.saving_picture) + "...")
                            .setProgress(100, 100, true).setLargeIcon(BitmapFactory
                                    .decodeResource(context.getResources(), R.drawable.ic_action_save));

                    NotificationManager mNotificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(6, mBuilder.build());

                    String url = webpage;
                    if (webpage.contains("insta")) {
                        url = url.substring(0, url.length() - 1) + "l";
                    }
                    URL mUrl = new URL(url);

                    Bitmap bitmap = BitmapFactory.decodeStream(mUrl.openConnection().getInputStream());

                    Random generator = new Random();
                    int n = 1000000;
                    n = generator.nextInt(n);
                    String fname = "Image-" + n;

                    Uri uri = IOUtils.saveImage(bitmap, fname, context);
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(uri, "image/*");

                    PendingIntent pending = PendingIntent.getActivity(context, 91, intent, 0);

                    mBuilder = new NotificationCompat.Builder(context).setContentIntent(pending)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.saved_picture) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.saved_picture) + "!")
                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
                                    R.drawable.ic_action_save));

                    mNotificationManager.notify(6, mBuilder.build());
                } catch (Exception e) {
                    e.printStackTrace();
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.error) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.error) + "...")
                            .setProgress(100, 100, true).setLargeIcon(BitmapFactory
                                    .decodeResource(context.getResources(), R.drawable.ic_action_save));

                    NotificationManager mNotificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(6, mBuilder.build());
                }
            }
        }).start();

        return true;

    case R.id.menu_quote:
        String text = tweet;

        switch (settings.quoteStyle) {
        case AppSettings.QUOTE_STYLE_TWITTER:
            text = " " + "https://twitter.com/" + screenName + "/status/" + tweetId;
            break;
        case AppSettings.QUOTE_STYLE_TALON:
            text = "\"@" + screenName + ": " + text + "\" ";
            break;
        case AppSettings.QUOTE_STYLE_RT:
            text = " RT @" + screenName + ": " + text;
            break;
        }

        Intent quote = new Intent(context, ComposeActivity.class);
        quote.putExtra("user", text);
        quote.putExtra("id", tweetId);

        startActivity(quote);

        return true;

    case R.id.menu_spam:
        new MarkSpam().execute();
        getSharedPreferences("com.klinker.android.twitter_world_preferences", 0).edit()
                .putBoolean("just_muted", true).commit();
        return super.onOptionsItemSelected(item);

    /*case R.id.menu_mute_hashtags:
        if (!hashtags[0].equals("")) {
            ArrayList<String> tags = new ArrayList<String>();
            if (hashtags != null) {
                for (String s : hashtags) {
                    if (!s.equals("")) {
                        tags.add("#" + s);
                    }
                }
            }
            
            final CharSequence[] fItems = new CharSequence[tags.size()];
            
            for (int i = 0; i < tags.size(); i++) {
                fItems[i] = tags.get(i);
            }
            
            final SharedPreferences sharedPreferences = context.getSharedPreferences("com.klinker.android.twitter_world_preferences",
                    0);
            
            if (fItems.length > 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setItems(fItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String touched = fItems[item] + "";
                        Toast.makeText(context, getResources().getString(R.string.muted) + " " + touched, Toast.LENGTH_SHORT).show();
                        touched = touched.replace("#", "") + " ";
            
                        String current = sharedPreferences.getString("muted_hashtags", "");
                        sharedPreferences.edit().putString("muted_hashtags", current + touched).commit();
                        sharedPreferences.edit().putBoolean("refresh_me", true).commit();
            
                        dialog.dismiss();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                String touched = fItems[0] + "";
                Toast.makeText(context, getResources().getString(R.string.muted) + " " + touched, Toast.LENGTH_SHORT).show();
                touched = touched.replace("#", "") + " ";
            
                String current = sharedPreferences.getString("muted_hashtags", "");
                sharedPreferences.edit().putString("muted_hashtags", current + touched).commit();
                sharedPreferences.edit().putBoolean("refresh_me", true).commit();
            
            }
        } else {
            Toast.makeText(context, getResources().getString(R.string.no_hashtags), Toast.LENGTH_SHORT).show();
        }
            
        PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("just_muted", true).commit();
        return super.onOptionsItemSelected(item);
            
    case R.id.menu_share_links:
        if (!otherLinks[0].equals("")) {
            ArrayList<String> urls = new ArrayList<String>();
            if (otherLinks != null) {
                for (String s : otherLinks) {
                    if (!s.equals("")) {
                        urls.add(s);
                    }
                }
            }
            
            final CharSequence[] fItems = new CharSequence[urls.size()];
            
            for (int i = 0; i < urls.size(); i++) {
                fItems[i] = urls.get(i);
            }
            
            if (fItems.length > 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setItems(fItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String touched = fItems[item] + "";
            
                        Intent intent=new Intent(android.content.Intent.ACTION_SEND);
                        intent.setType("text/plain");
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                        intent.putExtra(Intent.EXTRA_TEXT, touched);
                        context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.menu_share)));
            
                        dialog.dismiss();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                String touched = fItems[0] + "";
            
                Intent intent=new Intent(android.content.Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                intent.putExtra(Intent.EXTRA_TEXT, touched);
                context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.menu_share)));
            }
        } else {
            Toast.makeText(context, getResources().getString(R.string.no_links), Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);*/
    case R.id.menu_translate:
        try {
            String url = settings.translateURL + tweet;

            Uri uri = Uri.parse(url);

            Intent browser = new Intent(Intent.ACTION_VIEW, uri);
            browser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivity(browser);
        } catch (Exception e) {

        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.klinker.android.twitter.ui.tweet_viewer.TweetPager.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case android.R.id.home:
        onBackPressed();//from   ww w  . j  a v a  2 s .co m
        return true;

    case R.id.menu_delete_tweet:
        new DeleteTweet().execute();
        getSharedPreferences("com.klinker.android.twitter_world_preferences",
                Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE).edit()
                        .putBoolean("just_muted", true).commit();
        return true;

    case R.id.menu_share:
        String text1 = tweet;
        text1 = "@" + screenName + ": " + text1 + "\n\n" + "https://twitter.com/" + screenName + "/status/"
                + tweetId;
        Log.v("my_text_on_share", text1);
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("text/plain");
        share.putExtra(Intent.EXTRA_TEXT, text1);

        startActivity(share);
        return true;

    case R.id.menu_copy_text:
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("tweet_text", tweet);
        clipboard.setPrimaryClip(clip);
        return true;

    /*case R.id.menu_open_web:
        Uri weburi;
        try {
            weburi = Uri.parse(otherLinks[0]);
        } catch (Exception e) {
            weburi = Uri.parse(webpage);
        }
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, weburi);
        startActivity(launchBrowser);
            
        return true;*/

    case R.id.menu_save_image:

        new Thread(new Runnable() {
            @Override
            public void run() {

                Looper.prepare();

                try {
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.downloading) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.saving_picture) + "...")
                            .setProgress(100, 100, true).setLargeIcon(BitmapFactory
                                    .decodeResource(context.getResources(), R.drawable.ic_action_save));

                    NotificationManager mNotificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(6, mBuilder.build());

                    String url = webpage;
                    if (webpage.contains("insta")) {
                        url = url.substring(0, url.length() - 1) + "l";
                    }
                    URL mUrl = new URL(url);

                    Bitmap bitmap = BitmapFactory.decodeStream(mUrl.openConnection().getInputStream());

                    Random generator = new Random();
                    int n = 1000000;
                    n = generator.nextInt(n);
                    String fname = "Image-" + n;

                    Uri uri = IOUtils.saveImage(bitmap, fname, context);
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(uri, "image/*");

                    PendingIntent pending = PendingIntent.getActivity(context, 91, intent, 0);

                    mBuilder = new NotificationCompat.Builder(context).setContentIntent(pending)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.saved_picture) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.saved_picture) + "!")
                            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
                                    R.drawable.ic_action_save));

                    mNotificationManager.notify(6, mBuilder.build());
                } catch (Exception e) {
                    e.printStackTrace();
                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
                            .setSmallIcon(R.drawable.ic_stat_icon)
                            .setTicker(getResources().getString(R.string.error) + "...")
                            .setContentTitle(getResources().getString(R.string.app_name))
                            .setContentText(getResources().getString(R.string.error) + "...")
                            .setProgress(100, 100, true).setLargeIcon(BitmapFactory
                                    .decodeResource(context.getResources(), R.drawable.ic_action_save));

                    NotificationManager mNotificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    mNotificationManager.notify(6, mBuilder.build());
                }
            }
        }).start();

        return true;

    case R.id.menu_quote:
        String text = tweet;

        if (!settings.preferRT) {
            text = "\"@" + screenName + ": " + text + "\" ";
        } else {
            text = " RT @" + screenName + ": " + text;
        }

        Intent quote = new Intent(context, ComposeActivity.class);
        quote.putExtra("user", text);
        quote.putExtra("id", tweetId);

        startActivity(quote);

        return true;

    case R.id.menu_spam:
        new MarkSpam().execute();
        getSharedPreferences("com.klinker.android.twitter_world_preferences",
                Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE).edit()
                        .putBoolean("just_muted", true).commit();
        return super.onOptionsItemSelected(item);

    /*case R.id.menu_mute_hashtags:
        if (!hashtags[0].equals("")) {
            ArrayList<String> tags = new ArrayList<String>();
            if (hashtags != null) {
                for (String s : hashtags) {
                    if (!s.equals("")) {
                        tags.add("#" + s);
                    }
                }
            }
            
            final CharSequence[] fItems = new CharSequence[tags.size()];
            
            for (int i = 0; i < tags.size(); i++) {
                fItems[i] = tags.get(i);
            }
            
            final SharedPreferences sharedPreferences = context.getSharedPreferences("com.klinker.android.twitter_world_preferences",
                    Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
            
            if (fItems.length > 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setItems(fItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String touched = fItems[item] + "";
                        Toast.makeText(context, getResources().getString(R.string.muted) + " " + touched, Toast.LENGTH_SHORT).show();
                        touched = touched.replace("#", "") + " ";
            
                        String current = sharedPreferences.getString("muted_hashtags", "");
                        sharedPreferences.edit().putString("muted_hashtags", current + touched).commit();
                        sharedPreferences.edit().putBoolean("refresh_me", true).commit();
            
                        dialog.dismiss();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                String touched = fItems[0] + "";
                Toast.makeText(context, getResources().getString(R.string.muted) + " " + touched, Toast.LENGTH_SHORT).show();
                touched = touched.replace("#", "") + " ";
            
                String current = sharedPreferences.getString("muted_hashtags", "");
                sharedPreferences.edit().putString("muted_hashtags", current + touched).commit();
                sharedPreferences.edit().putBoolean("refresh_me", true).commit();
            
            }
        } else {
            Toast.makeText(context, getResources().getString(R.string.no_hashtags), Toast.LENGTH_SHORT).show();
        }
            
        PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("just_muted", true).commit();
        return super.onOptionsItemSelected(item);
            
    case R.id.menu_share_links:
        if (!otherLinks[0].equals("")) {
            ArrayList<String> urls = new ArrayList<String>();
            if (otherLinks != null) {
                for (String s : otherLinks) {
                    if (!s.equals("")) {
                        urls.add(s);
                    }
                }
            }
            
            final CharSequence[] fItems = new CharSequence[urls.size()];
            
            for (int i = 0; i < urls.size(); i++) {
                fItems[i] = urls.get(i);
            }
            
            if (fItems.length > 1) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setItems(fItems, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int item) {
                        String touched = fItems[item] + "";
            
                        Intent intent=new Intent(android.content.Intent.ACTION_SEND);
                        intent.setType("text/plain");
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                        intent.putExtra(Intent.EXTRA_TEXT, touched);
                        context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.menu_share)));
            
                        dialog.dismiss();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                String touched = fItems[0] + "";
            
                Intent intent=new Intent(android.content.Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                intent.putExtra(Intent.EXTRA_TEXT, touched);
                context.startActivity(Intent.createChooser(intent, context.getResources().getString(R.string.menu_share)));
            }
        } else {
            Toast.makeText(context, getResources().getString(R.string.no_links), Toast.LENGTH_SHORT).show();
        }
        return super.onOptionsItemSelected(item);*/
    case R.id.menu_translate:
        try {
            String query = tweet.replaceAll(" ", "+");
            String url = "http://translate.google.com/#auto|en|" + tweet;
            Uri uri = Uri.parse(url);

            Intent browser = new Intent(Intent.ACTION_VIEW, uri);
            browser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivity(browser);
        } catch (Exception e) {

        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:eu.dirtyharry.androidopsiadmin.Main.java

public void getOPSIDepots() {

    final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait),
            getString(R.string.pd_getdepots), true);
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();/* w ww .  j a va2  s  .c  o m*/
            if (GlobalVar.getInstance().getError().equals("null")) {
                if (doit.equals("true")) {

                    JSONArray result = new JSONArray();
                    try {
                        result = opsiresult.getJSONArray("result");
                        depots = new String[result.length()];
                        for (int i = 0; i < result.length(); i++) {
                            depots[i] = result.getString(i);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
                    builder.setTitle(getString(R.string.gen_choose));
                    builder.setSingleChoiceItems(depots, -1, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int item) {
                            dialog.dismiss();
                            String depot = depots[item];
                            choosendepot = depot;

                            getOPSIDepotConfig(depot);

                        }
                    });
                    AlertDialog alert = builder.create();
                    alert.show();

                } else if (doit.equals("serverdown")) {
                    Toast.makeText(Main.this, String.format(getString(R.string.to_servernotrechable), serverip),
                            // serverip + " "
                            // + getString(R.string.to_servernotrechable),
                            Toast.LENGTH_LONG).show();
                }
            } else {
                new Functions().msgBox(Main.this, getString(R.string.gen_title_error),
                        GlobalVar.getInstance().getError(), false);
            }

        }
    };
    Thread checkUpdate = new Thread() {
        public void run() {
            Looper.prepare();
            JSONArray JSONparams = new JSONArray();
            if (Networking.isServerUp(serverip, serverport, serverusername, serverpasswd)) {
                opsiresult = new JSONObject();
                opsiresult = eu.dirtyharry.androidopsiadmin.Networking.opsiGetJSONObject("rpc", serverip,
                        serverport, "getDepotIds_list", JSONparams, serverusername, serverpasswd);
                doit = "true";
            } else {
                doit = "serverdown";
                //
            }
            handler.sendEmptyMessage(0);
        }
    };
    checkUpdate.start();
}

From source file:app.axe.imooc.zxing.app.CaptureActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        uri = data.getData();/*  w  w w.j  a v  a2  s  .c o m*/
        new Thread(new Runnable() {
            @Override
            public void run() {

                Result result = scanningImage(uri);
                if (result == null) {
                    Looper.prepare();
                    Toast.makeText(getApplicationContext(), "?", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                } else {
                    // ???
                    String recode = (result.toString());
                    Intent data = new Intent();
                    data.putExtra("result", recode);
                    setResult(300, data);
                    finish();
                }
            }
        }).start();
    }
}

From source file:fi.mikuz.boarder.gui.DropboxMenu.java

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_share:
        Thread thread = new Thread() {
            public void run() {
                Looper.prepare();
                try {
                    final ArrayList<String> boards = mCbla.getAllSelectedTitles();
                    if (!(mOperation == DOWNLOAD_OPERATION)) {
                        mToastMessage = "Select 'Download' mode";
                        mHandler.post(mShowToast);
                    } else if (boards.size() < 1) {
                        mToastMessage = "Select boards to share";
                        mHandler.post(mShowToast);
                    } else {
                        String shareString = "I want to share some cool soundboards to you!\n\n"
                                + "To use the boards you need to have Boarder for Android:\n"
                                + ExternalIntent.mExtLinkMarket + "\n\n" + "Here are the boards:\n";

                        for (String board : boards) {
                            shareString += board + " - " + mApi.createCopyRef("/" + board).copyRef + "\n";
                        }/*w  w  w.j  ava2s  .  c o m*/

                        shareString += "\n\n" + "Importing a board:\n" + "1. Open Boarder'\n"
                                + "2. Open Dropbox from menu in 'Soundboard Menu'\n"
                                + "3. Open 'Import share' from menu\n"
                                + "4. Copy a reference from above to textfield\n";

                        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
                        sharingIntent.setType("text/plain");
                        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Sharing boards");
                        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareString);
                        startActivity(Intent.createChooser(sharingIntent, "Share via"));
                    }
                } catch (DropboxException e) {
                    Log.e(TAG, "Unable to share", e);
                }
            }
        };
        thread.start();
        return true;

    case R.id.menu_import_share:
        LayoutInflater removeInflater = (LayoutInflater) DropboxMenu.this
                .getSystemService(LAYOUT_INFLATER_SERVICE);
        View importLayout = removeInflater.inflate(R.layout.dropbox_menu_alert_import_share,
                (ViewGroup) findViewById(R.id.alert_remove_sound_root));

        AlertDialog.Builder importBuilder = new AlertDialog.Builder(DropboxMenu.this);
        importBuilder.setView(importLayout);
        importBuilder.setTitle("Import share");

        final EditText importCodeInput = (EditText) importLayout.findViewById(R.id.importCodeInput);
        final EditText importNameInput = (EditText) importLayout.findViewById(R.id.importNameInput);

        importBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                t = new Thread() {
                    public void run() {
                        Looper.prepare();
                        try {
                            mApi.addFromCopyRef(importCodeInput.getText().toString(),
                                    "/" + importNameInput.getText().toString());
                            mToastMessage = "Download the board from 'Download'";
                            mHandler.post(mShowToast);
                        } catch (DropboxException e) {
                            Log.e(TAG, "Unable to get shared board", e);
                        }
                    }
                };
                t.start();
            }
        });

        importBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        });
        importBuilder.show();
        return true;
    }

    return super.onMenuItemSelected(featureId, item);
}

From source file:eu.dirtyharry.androidopsiadmin.Main.java

public void event_opsisenddepotconfigchanges() {
    final ProgressDialog dialog = ProgressDialog.show(Main.this, getString(R.string.gen_title_pleasewait),
            String.format(getString(R.string.pd_senddepotchangesfor), choosendepot), true);
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dialog.dismiss();//  w  w w. j a v  a 2s  . c om
            if (!GlobalVar.getInstance().getError().equals("null")) {
                new Functions().msgBox(Main.this, getString(R.string.gen_title_error),
                        GlobalVar.getInstance().getError(), false);
            }
        }
    };
    Thread checkUpdate = new Thread() {
        public void run() {
            Looper.prepare();
            JSONArray test = new JSONArray();
            JSONObject params = new JSONObject();
            try {
                params.put("id", choosendepot);
                params.put("type", "OpsiConfigserver");
                for (int i = 0; i < resultconfignames.size(); i++) {
                    params.put(resultconfignames.get(i), resultconfigvalues.get(i));
                }
            } catch (JSONException e1) {
                e1.printStackTrace();
            }

            test.put(params);
            opsiresult = new JSONObject();
            opsiresult = eu.dirtyharry.androidopsiadmin.Networking.opsiGetJSONObject("rpc", serverip,
                    serverport, "host_updateObject", test, serverusername, serverpasswd);
            try {
                if (!opsiresult.isNull("error")) {
                    GlobalVar.getInstance().setError(opsiresult.getString("error"));
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            handler.sendEmptyMessage(0);
        }
    };
    checkUpdate.start();
}

From source file:com.qa.perf.emmageeplus.service.EmmageeService.java

@Override
public void onDestroy() {
    Log.i(LOG_TAG, "service onDestroy");
    if (windowManager != null) {
        windowManager.removeView(viFloatingWindow);
        viFloatingWindow = null;/*  ww w.jav  a 2s.  c  o m*/
    }
    handler.removeCallbacks(task);
    closeOpenedStream();
    // replace the start time in file
    if (!BLANK_STRING.equals(startTime)) {
        replaceFileString(resultFilePath, START_TIME,
                getString(R.string.start_time) + startTime + Constants.LINE_END);
    } else {
        replaceFileString(resultFilePath, START_TIME, BLANK_STRING);
    }
    isStop = true;
    unregisterReceiver(batteryBroadcast);

    new Thread(new Runnable() {
        @Override
        public void run() {
            boolean isSendSuccessfully = false;
            try {
                isSendSuccessfully = MailSender.sendTextMail(sender, des.decrypt(password), smtp,
                        "Emmagee Performance Test Report", "see attachment", resultFilePath, receivers);
            } catch (Exception e) {
                Log.w(LOG_TAG, "sendTextMail: ", e);
                isSendSuccessfully = false;
            }
            Looper.prepare();
            if (isSendSuccessfully) {
                Toast.makeText(EmmageeService.this, getString(R.string.send_success_toast) + recipients,
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(EmmageeService.this,
                        getString(R.string.send_fail_toast) + EmmageeService.resultFilePath, Toast.LENGTH_LONG)
                        .show();
            }
            Looper.loop();
        }
    }).start();

    super.onDestroy();
    stopForeground(true);
}

From source file:org.acra.ErrorReporter.java

/**
 * Try to send a report, if an error occurs stores a report file for a later
 * attempt.//www.  j  a v a2s.com
 *
 * @param reportBuilder The report builder used to assemble the report
 */
private void report(final ReportBuilder reportBuilder) {

    if (!enabled) {
        return;
    }

    try {
        exceptionHandlerInitializer.initializeExceptionHandler(this);
    } catch (Exception exceptionInRunnable) {
        ACRA.log.d(LOG_TAG, "Failed to initlize " + exceptionHandlerInitializer + " from #handleException");
    }

    boolean sendOnlySilentReports = false;
    ReportingInteractionMode reportingInteractionMode;
    if (!reportBuilder.mForceSilent) {
        // No interaction mode defined, we assume it has been set during
        // ACRA.initACRA()
        reportingInteractionMode = ACRA.getConfig().mode();
    } else {
        reportingInteractionMode = ReportingInteractionMode.SILENT;

        // An interaction mode has been provided. If ACRA has been
        // initialized with a non SILENT mode and this mode is overridden
        // with SILENT, then we have to send only reports which have been
        // explicitly declared as silent via handleSilentException().
        if (ACRA.getConfig().mode() != ReportingInteractionMode.SILENT) {
            sendOnlySilentReports = true;
        }
    }

    final boolean shouldDisplayToast = reportingInteractionMode == ReportingInteractionMode.TOAST
            || (ACRA.getConfig().resToastText() != 0
                    && (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION
                            || reportingInteractionMode == ReportingInteractionMode.DIALOG));

    final TimeHelper sentToastTimeMillis = new TimeHelper();
    if (shouldDisplayToast) {
        new Thread() {

            /*
             * (non-Javadoc)
             *
             * @see java.lang.Thread#run()
             */
            @Override
            public void run() {
                Looper.prepare();
                ToastSender.sendToast(mContext, ACRA.getConfig().resToastText(), Toast.LENGTH_LONG);
                sentToastTimeMillis.setInitialTimeMillis(System.currentTimeMillis());
                Looper.loop();
            }

        }.start();

        // We will wait a few seconds at the end of the method to be sure
        // that the Toast can be read by the user.
    }

    final CrashReportData crashReportData = crashReportDataFactory.createCrashData(reportBuilder.mMessage,
            reportBuilder.mException, reportBuilder.mCustomData, reportBuilder.mForceSilent,
            reportBuilder.mUncaughtExceptionThread);

    // Always write the report file

    final String reportFileName = getReportFileName(crashReportData);
    saveCrashReportFile(reportFileName, crashReportData);

    if (reportBuilder.mEndsApplication && !ACRA.getConfig().sendReportsAtShutdown()) {
        endApplication(reportBuilder.mUncaughtExceptionThread, reportBuilder.mException);
    }

    SendWorker sender = null;

    if (reportingInteractionMode == ReportingInteractionMode.SILENT
            || reportingInteractionMode == ReportingInteractionMode.TOAST
            || prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false)) {

        // Approve and then send reports now
        ACRA.log.d(LOG_TAG, "About to start ReportSenderWorker from #handleException");
        sender = startSendingReports(sendOnlySilentReports, true);
        if ((reportingInteractionMode == ReportingInteractionMode.SILENT) && !reportBuilder.mEndsApplication) {
            // Report is being sent silently and the application is not ending.
            // So no need to wait around for the sender to complete.
            return;
        }

    } else if (reportingInteractionMode == ReportingInteractionMode.NOTIFICATION) {
        ACRA.log.d(LOG_TAG, "Creating Notification.");
        createNotification(reportFileName, reportBuilder);
    }

    toastWaitEnded = true;
    if (shouldDisplayToast) {
        // A toast is being displayed, we have to wait for its end before doing anything else.
        // The toastWaitEnded flag will be checked before any other operation.
        toastWaitEnded = false;
        new Thread() {

            @Override
            public void run() {
                ACRA.log.d(LOG_TAG,
                        "Waiting for " + ACRAConstants.TOAST_WAIT_DURATION + " millis from "
                                + sentToastTimeMillis.initialTimeMillis + " currentMillis="
                                + System.currentTimeMillis());
                while (sentToastTimeMillis.getElapsedTime() < ACRAConstants.TOAST_WAIT_DURATION) {
                    try {
                        // Wait a bit to let the user read the toast
                        Thread.sleep(100);
                    } catch (InterruptedException e1) {
                        ACRA.log.d(LOG_TAG, "Interrupted while waiting for Toast to end.", e1);
                    }
                }
                toastWaitEnded = true;
            }
        }.start();
    }

    // Start an AsyncTask waiting for the end of the sender.
    // Once sent, call endApplication() if reportBuilder.mEndApplication
    final SendWorker worker = sender;
    final boolean showDirectDialog = (reportingInteractionMode == ReportingInteractionMode.DIALOG)
            && !prefs.getBoolean(ACRA.PREF_ALWAYS_ACCEPT, false);

    new Thread() {

        @Override
        public void run() {
            // We have to wait for the toast display to be completed.
            ACRA.log.d(LOG_TAG, "Waiting for Toast");
            while (!toastWaitEnded) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                    ACRA.log.d(LOG_TAG, "Error : ", e1);
                }
            }
            ACRA.log.d(LOG_TAG, "Finished waiting for Toast");

            // We have to wait for the worker job to be completed.
            if (worker != null) {
                ACRA.log.d(LOG_TAG, "Waiting for Worker");
                while (worker.isAlive()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e1) {
                        ACRA.log.d(LOG_TAG, "Error : ", e1);
                    }
                }
                ACRA.log.d(LOG_TAG, "Finished waiting for Worker");
            }

            if (showDirectDialog) {
                // Create a new activity task with the confirmation dialog.
                // This new task will be persisted on application restart
                // right after its death.
                ACRA.log.d(LOG_TAG, "Creating CrashReportDialog for " + reportFileName);
                final Intent dialogIntent = createCrashReportDialogIntent(reportFileName, reportBuilder);
                dialogIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(dialogIntent);
            }

            ACRA.log.d(LOG_TAG,
                    "Wait for Toast + worker ended. Kill Application ? " + reportBuilder.mEndsApplication);

            if (reportBuilder.mEndsApplication) {
                endApplication(reportBuilder.mUncaughtExceptionThread, reportBuilder.mException);
            }
        }
    }.start();
}

From source file:eu.dirtyharry.androidopsiadmin.Main.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == GET_QR && resultCode == RESULT_OK) {
        contents = data.getExtras().getString("la.droid.qr.result");
        if (checkQR(contents)) {
            try {
                pc = (JSONObject) new JSONTokener(contents).nextValue();
                hosttocheck = pc.getString("dns");
            } catch (JSONException e) {
                e.printStackTrace();//from  www. ja va  2s.c  o  m
            }
            final ProgressDialog dialog = ProgressDialog.show(Main.this,
                    getString(R.string.gen_title_pleasewait),
                    String.format(getString(R.string.pd_checkifopsiclientexists), hosttocheck), true);
            final Handler handler = new Handler() {
                public void handleMessage(Message msg) {
                    if (hostexistsinopsi && doit.equals("true")) {
                        if (customtags) {
                            Intent i = new Intent(Main.this, ShowBarcodeData.class);
                            Bundle b = new Bundle();
                            b.putString("qrdata", contents);
                            i.putExtras(b);
                            startActivity(i);
                        } else {
                            Intent i = new Intent(Main.this, ShowOpsiClientOptions.class);
                            Bundle b = new Bundle();
                            b.putString("qrdata", contents);
                            i.putExtras(b);
                            startActivity(i);
                        }
                    } else if (!hostexistsinopsi) {
                        new Functions().msgBox(Main.this, getString(R.string.gen_title_error),
                                String.format(getString(R.string.general_noopsihost), hosttocheck), false);
                    } else {
                        Toast.makeText(Main.this,
                                String.format(getString(R.string.to_servernotrechable), serverip),
                                Toast.LENGTH_LONG).show();
                    }
                    dialog.dismiss();
                }
            };

            Thread checkUpdate = new Thread() {
                public void run() {
                    Looper.prepare();

                    if (eu.dirtyharry.androidopsiadmin.Networking.isServerUp(serverip, serverport,
                            serverusername, serverpasswd)) {
                        doit = "true";
                        if (eu.dirtyharry.androidopsiadmin.Networking.checkIfHostExistsInOpsi(hosttocheck,
                                serverip, serverport, serverusername, serverpasswd)) {
                            hostexistsinopsi = true;
                        } else {
                            hostexistsinopsi = false;
                        }
                    } else {
                        doit = "serverdown";
                    }
                    handler.sendEmptyMessage(0);

                }
            };
            checkUpdate.start();

        } else {
            new Functions().msgBox(Main.this, getString(R.string.gen_title_error),
                    getString(R.string.at_novalidqr), false);
        }
    } else if (requestCode == GET_OPSI_CLIENT_REQUEST && resultCode == Activity.RESULT_OK) {
        if (data.getStringExtra("message").equals("refresh")) {
            getOpsiClientsTask();
        }
        // } else if (requestCode == SHOW_OPSI_DEPOT_REQUEST
        // && resultCode == Activity.RESULT_OK) {
        // resultconfignames = data.getExtras().getStringArrayList(
        // "choosenones");
        // resultconfigvalues = data.getExtras().getStringArrayList(
        // "choosenonesvalues");
        // event_opsisenddepotconfigchanges();
    }
}