Example usage for android.content Intent addCategory

List of usage examples for android.content Intent addCategory

Introduction

In this page you can find the example usage for android.content Intent addCategory.

Prototype

public @NonNull Intent addCategory(String category) 

Source Link

Document

Add a new category to the intent.

Usage

From source file:com.github.dfa.diaspora_android.activity.ShareActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override//from w  w w  .j  ava  2s.c om
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main__activity);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (toolbar != null) {
        toolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Helpers.isOnline(ShareActivity.this)) {
                    Intent intent = new Intent(ShareActivity.this, MainActivity.class);
                    startActivityForResult(intent, 100);
                    overridePendingTransition(0, 0);
                    finish();
                } else {
                    Snackbar.make(swipeView, R.string.no_internet, Snackbar.LENGTH_LONG).show();
                }
            }
        });
    }
    setTitle(R.string.new_post);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    swipeView.setEnabled(false);

    podDomain = ((App) getApplication()).getSettings().getPodDomain();

    webView = (WebView) findViewById(R.id.webView);
    webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    WebSettings wSettings = webView.getSettings();
    wSettings.setJavaScriptEnabled(true);
    wSettings.setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= 21)
        wSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    /*
     * WebViewClient
     */
    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.d(TAG, url);
            if (!url.contains(podDomain)) {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
                return true;
            }
            return false;

        }

        public void onPageFinished(WebView view, String url) {
            Log.i(TAG, "Finished loading URL: " + url);
        }
    });

    /*
     * WebChromeClient
     */
    webView.setWebChromeClient(new WebChromeClient() {

        public void onProgressChanged(WebView wv, int progress) {
            progressBar.setProgress(progress);

            if (progress > 0 && progress <= 60) {
                Helpers.getNotificationCount(wv);
            }

            if (progress > 60) {
                Helpers.applyDiasporaMobileSiteChanges(wv);
            }

            if (progress == 100) {
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null)
                mFilePathCallback.onReceiveValue(null);

            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Snackbar.make(getWindow().findViewById(R.id.main__layout), "Unable to get image",
                            Snackbar.LENGTH_LONG).show();
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });

    if (savedInstanceState == null) {
        if (Helpers.isOnline(ShareActivity.this)) {
            webView.loadUrl("https://" + podDomain + "/status_messages/new");
        } else {
            Snackbar.make(getWindow().findViewById(R.id.main__layout), R.string.no_internet,
                    Snackbar.LENGTH_LONG).show();
        }
    }

    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            if (intent.hasExtra(Intent.EXTRA_SUBJECT)) {
                handleSendSubject(intent);
            } else {
                handleSendText(intent);
            }
        } else if (type.startsWith("image/")) {
            // TODO Handle single image being sent -> see manifest
            handleSendImage(intent);
        }
        //} else {
        // Handle other intents, such as being started from the home screen
    }

}

From source file:com.example.lilach.alsweekathon_new.MainActivity.java

@Override
public void onBackPressed() {
    if (mState == UART_PROFILE_CONNECTED) {
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);//  w w  w  .j a va2  s  .c o  m
        showMessage("nRFUART's running in background.\n             Disconnect to exit");
    } else {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.popup_title)
                .setMessage(R.string.popup_message)
                .setPositiveButton(R.string.popup_yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setNegativeButton(R.string.popup_no, null).show();
    }
}

From source file:com.google.android.testing.nativedriver.server.AndroidNativeDriver.java

/** Start a new activity either in a new task or the current task. */
public void startActivity(Class<?> activityClass) {
    Intent intent = new Intent(context.getInstrumentation().getContext(), activityClass);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    context.getInstrumentation().startActivitySync(intent);
}

From source file:com.b44t.messenger.NotificationsController.java

private static String getLauncherClassName(Context context) {
    try {//from   ww w.jav  a  2s .c om
        PackageManager pm = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkgName = resolveInfo.activityInfo.applicationInfo.packageName;
            if (pkgName.equalsIgnoreCase(context.getPackageName())) {
                return resolveInfo.activityInfo.name;
            }
        }
    } catch (Throwable e) {
        FileLog.e("messenger", e);
    }
    return null;
}

From source file:net.evecom.androidecssp.base.BaseWebActivity.java

/**
 * /* w  ww  .  ja  v  a 2s.  c o  m*/
 * 
 * 
 * @author Mars zhang
 * @created 2015-11-25 2:11:17
 * @param file
 * @return
 */
public Intent getFileIntent(File file) {
    // Uri uri = Uri.parse("http://m.ql18.com.cn/hpf10/1.pdf");
    Uri uri = Uri.fromFile(file);
    String type = getMIMEType(file);
    Log.i("tag", "type=" + type);
    Intent intent = new Intent("android.intent.action.VIEW");
    intent.addCategory("android.intent.category.DEFAULT");
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(uri, type);
    return intent;
}

From source file:org.universAAL.android.proxies.ServiceCalleeProxy.java

/**
 * This is an auxiliary method that invokes this proxy when a service
 * request matched in the R API server, and the ServiceCall was sent here
 * through GCM. We receive a ServiceCall not a BusMessage nor a
 * ServiceRequest. It sends the response back to the R API rather than
 * through the inner bus.//from   w  ww  . j  av  a2s  . co m
 * 
 * @param scall
 *            The ServiceCall as received from R API through GCM.
 * @param origincall
 *            The original ServiceCall URI as specified by the server. It is
 *            not the same as scall.getURI() since that object is created
 *            here in the client.
 */
public void handleCallFromGCM(ServiceCall scall, String origincall) {
    Boolean needsOuts = (Boolean) scall.getNonSemanticInput(AppConstants.UAAL_META_PROP_NEEDSOUTPUTS);
    Context ctxt = contextRef.get();
    if (ctxt != null) {
        // Prepare an intent for sending to Android grounded service
        Intent serv = new Intent(action);
        serv.addCategory(category);
        boolean expecting = false;
        // If a response is expected, prepare a callback receiver (which must be called by uaalized app)
        if ((replyAction != null && !replyAction.isEmpty())
                && (replyCategory != null && !replyCategory.isEmpty())) {
            // Tell the destination where to send the reply
            serv.putExtra(AppConstants.ACTION_META_REPLYTOACT, replyAction);
            serv.putExtra(AppConstants.ACTION_META_REPLYTOCAT, replyCategory);
            // Register the receiver for the reply
            receiver = new ServiceCalleeProxyReceiverGCM(origincall);
            IntentFilter filter = new IntentFilter(replyAction);
            filter.addCategory(replyCategory);
            ctxt.registerReceiver(receiver, filter);
            expecting = true;
        } else if (needsOuts != null && needsOuts.booleanValue()) {
            // No reply* fields set, but caller still needs a response, lets
            // build one (does not work for callers outside android MW)
            Random r = new Random();
            String action = AppConstants.ACTION_REPLY + r.nextInt();
            serv.putExtra(AppConstants.ACTION_META_REPLYTOACT, action);
            serv.putExtra(AppConstants.ACTION_META_REPLYTOCAT, Intent.CATEGORY_DEFAULT);
            // Register the receiver for the reply
            receiver = new ServiceCalleeProxyReceiverGCM(origincall);
            IntentFilter filter = new IntentFilter(action);
            filter.addCategory(Intent.CATEGORY_DEFAULT);
            ctxt.registerReceiver(receiver, filter);
            expecting = true;
        }
        // Take the inputs from the call and put them in the intent
        if (inputURItoExtraKEY != null && !inputURItoExtraKEY.isEmpty()) {
            VariableSubstitution.putCallInputsAsIntentExtras(scall, serv, inputURItoExtraKEY);
        }
        // Flag to avoid feeding back the intent to bus when intent is the same in app and in callerproxy 
        serv.putExtra(AppConstants.ACTION_META_FROMPROXY, true);
        // Send the intent to Android grounded service
        ComponentName started = null;
        try {
            // HACK: In android 5.0 it is forbidden to send implicit service intents like this one 
            started = ctxt.startService(serv);
        } catch (Exception e) {
            // Therefore if it fails, fail silently and try again with broadcast receivers
            started = null;
        }
        if (started == null) {
            // No android service was there, try with broadcast. Before, here it used to send failure response
            ctxt.sendBroadcast(serv); // No way to know if received. If no response, bus will timeout (?)
        } else if (!expecting) {
            // There is no receiver waiting a response, send success now
            ServiceResponse resp = new ServiceResponse(CallStatus.succeeded);
            sendResponseGCM(resp, origincall);
        }
        //TODO Handle timeout
    }
}

From source file:edu.mines.letschat.GcmIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();//w  w  w  .  j av  a 2  s .co  m
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    // The getMessageType() intent parameter must be the intent you received
    // in your BroadcastReceiver.
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) { // has effect of unparcelling Bundle
        /*
         * Filter messages based on message type. Since it is likely that GCM will be
         * extended in the future with new message types, just ignore any message types you're
         * not interested in, or that you don't recognize.
         */
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            sendNotification("Send error: " + extras.toString(), "0");
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            sendNotification("Deleted messages on server: " + extras.toString(), "0");
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            // This loop represents the service doing some work.
            //                for (int i = 0; i < 5; i++) {
            //                    Log.i(TAG, "Working... " + (i + 1)
            //                            + "/5 @ " + SystemClock.elapsedRealtime());
            //                    try {
            //                        Thread.sleep(5000);
            //                    } catch (InterruptedException e) {
            //                    }
            //                }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.

            String message = (String) extras.get("message");
            messages.add(message);

            String picture = (String) extras.get("picture");

            String senderID = (String) extras.get("sender");
            String recipientID = (String) extras.get("recipient");
            sendNotification(message, senderID);
            Log.v(TAG, "Received: " + message);

            Log.i(TAG, "Received: " + extras.toString());
            Intent resultBroadCastIntent = new Intent();
            /*set action here*/
            resultBroadCastIntent.setAction(
                    edu.mines.letschat.MessageActivity.TextCapitalizeResultReceiver.ACTION_TEXT_CAPITALIZED);
            /*set intent category as default*/
            resultBroadCastIntent.addCategory(Intent.CATEGORY_DEFAULT);

            /*add data to intent*/
            resultBroadCastIntent.putExtra(OUTPUT_TEXT, message);
            //              Log.v(TAG, "Sender id " + senderID + " recieve id " + recipientID);
            Log.v(TAG, picture);
            Conversation convo = new Conversation(getApplicationContext(), senderID, recipientID, message,
                    false, picture);
            convo.save();

            if (!picture.isEmpty()) {
                new DownloadImage(picture).execute();
            }

            /*send broadcast */
            sendBroadcast(resultBroadCastIntent);
        }
    }
    // Release the wake lock provided by the WakefulBroadcastReceiver.
    GcmBroadcastReviever.completeWakefulIntent(intent);
}

From source file:com.orange.ocara.ui.activity.ListAuditActivity.java

private void createNewDocument(String path) {
    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType(//from ww w . jav  a  2 s .c  o m
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(path)));
    startActivityForResult(intent, ACTION_CREATE_NEW_DOCUMENT);
}

From source file:jieehd.villain.updater.VillainUpdater.java

private boolean haveNetworkConnection() {
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo) {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                haveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                haveConnectedMobile = true;

    }//  www. j a  v  a  2 s.co  m
    if (haveConnectedWifi == false && haveConnectedMobile == false) {
        Log.d("Network State", "false");
        AlertDialog.Builder alert = new AlertDialog.Builder(VillainUpdater.this);
        alert.setTitle("No Data Connection!");
        alert.setMessage(
                "You have no data connection, click ok to turn on WiFi or Mobile Data in order to check for OTA updates.");
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                // TODO Auto-generated method stub
                final Intent intent = new Intent(Intent.ACTION_MAIN, null);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                final ComponentName cn = new ComponentName("com.android.settings",
                        "com.android.settings.wifi.WifiSettings");
                intent.setComponent(cn);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }

        });
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                return;
            }
        });
        alert.show();

    } else {
        download();
    }
    return haveConnectedWifi || haveConnectedMobile;
}