Example usage for android.content Intent setAction

List of usage examples for android.content Intent setAction

Introduction

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

Prototype

public @NonNull Intent setAction(@Nullable String action) 

Source Link

Document

Set the general action to be performed.

Usage

From source file:com.exercise.AndroidClient.AndroidClient.java

public void showDownload(View view) {
    Intent i = new Intent();
    i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
    startActivity(i);//from   w w w  .ja  v a 2  s .  co  m
}

From source file:gov.wa.wsdot.android.wsdot.service.CamerasSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/*  ww w  .  ja  v  a 2 s . c  o  m*/
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";

    /** 
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, projection, Caches.CACHE_TABLE_NAME + " LIKE ?",
                new String[] { "cameras" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaDays = (now - lastUpdated) / DateUtils.DAY_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaDays + " day(s)");
            shouldUpdate = (Math.abs(now - lastUpdated) > (7 * DateUtils.DAY_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();

        try {
            URL url = new URL(CAMERAS_URL);
            URLConnection urlConn = url.openConnection();

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

            String jsonFile = "";
            String line;
            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("cameras");
            JSONArray items = result.getJSONArray("items");
            List<ContentValues> cams = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = items.getJSONObject(j);
                ContentValues cameraData = new ContentValues();

                cameraData.put(Cameras.CAMERA_ID, item.getString("id"));
                cameraData.put(Cameras.CAMERA_TITLE, item.getString("title"));
                cameraData.put(Cameras.CAMERA_URL, item.getString("url"));
                cameraData.put(Cameras.CAMERA_LATITUDE, item.getString("lat"));
                cameraData.put(Cameras.CAMERA_LONGITUDE, item.getString("lon"));
                cameraData.put(Cameras.CAMERA_HAS_VIDEO, item.getString("video"));
                cameraData.put(Cameras.CAMERA_ROAD_NAME, item.getString("roadName"));

                if (starred.contains(Integer.parseInt(item.getString("id")))) {
                    cameraData.put(Cameras.CAMERA_IS_STARRED, 1);
                }

                cams.add(cameraData);
            }

            // Purge existing cameras covered by incoming data
            resolver.delete(Cameras.CONTENT_URI, null, null);
            // Bulk insert all the new cameras
            resolver.bulkInsert(Cameras.CONTENT_URI, cams.toArray(new ContentValues[cams.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + " LIKE ?",
                    new String[] { "cameras" });

            responseString = "OK";
        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }
    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.CAMERAS_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}

From source file:gov.wa.wsdot.android.wsdot.service.FerriesSchedulesSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;//from  w  w w. j a  v a2 s  .c  o  m
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";
    DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a");

    /** 
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "ferries_schedules" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min");
            shouldUpdate = (Math.abs(now - lastUpdated) > (30 * DateUtils.MINUTE_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();

        try {
            URL url = new URL(FERRIES_SCHEDULES_URL);
            URLConnection urlConn = url.openConnection();

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

            String jsonFile = "";
            String line;

            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONArray items = new JSONArray(jsonFile);
            List<ContentValues> schedules = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int i = 0; i < numItems; i++) {
                JSONObject item = items.getJSONObject(i);
                ContentValues schedule = new ContentValues();
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ID, item.getInt("RouteID"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_TITLE, item.getString("Description"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_DATE, item.getString("Date"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ALERT, item.getString("RouteAlert"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_UPDATED, dateFormat
                        .format(new Date(Long.parseLong(item.getString("CacheDate").substring(6, 19)))));

                if (starred.contains(item.getInt("RouteID"))) {
                    schedule.put(FerriesSchedules.FERRIES_SCHEDULE_IS_STARRED, 1);
                }

                schedules.add(schedule);
            }

            // Purge existing travel times covered by incoming data
            resolver.delete(FerriesSchedules.CONTENT_URI, null, null);
            // Bulk insert all the new travel times
            resolver.bulkInsert(FerriesSchedules.CONTENT_URI,
                    schedules.toArray(new ContentValues[schedules.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + "=?",
                    new String[] { "ferries_schedules" });

            responseString = "OK";
        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }

    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.FERRIES_SCHEDULES_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);

}

From source file:com.altcanvas.twitspeak.TwitSpeakActivity.java

private void promptTTSInstall() {
    AlertDialog ttsInstallDlg = new AlertDialog.Builder(this).create();
    ttsInstallDlg.setMessage(getString(R.string.tts_install_msg));
    ttsInstallDlg.setTitle(getString(R.string.tts_install_title));

    ttsInstallDlg.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(R.string.proceed_str),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();/*from ww  w  .j  ava 2  s.  c  o m*/
                    Intent installIntent = new Intent();
                    installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                    startActivity(installIntent);
                }
            });

    ttsInstallDlg.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.cancel_str),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    finish();
                }
            });
}

From source file:com.mobilesolutionworks.android.httpcache.HttpCacheLoaderImpl.java

public boolean deliverResult(HttpCache tag) {
    boolean contentChanged = mTag != null;
    if (mTag != null && mTag != tag) {
        mTag.close();//ww  w .ja  v a2  s .c o  m
    }

    mTag = tag;

    boolean noCache = mBuilder.isNoCache() && !contentChanged;
    boolean dispatchRequest = noCache;
    boolean deliverResult = false;

    if (tag.loaded) {
        if (contentChanged) {
            // content change indicating that service had returned the data
            mTag.loadFinished = true;
            deliverResult = true;
            dispatchRequest = false;
        } else {
            // new request
            if (mTag.error != 0 || // current cache is invalid
                    !mTag.remote.equals(mBuilder.remoteUri()) || // remote uri changed
                    mTag.expiry < System.currentTimeMillis() || // data expired
                    (mBuilder.keepFresh()
                            && mTag.expiry - System.currentTimeMillis() > mBuilder.cacheExpiry() * 1000) // new expiry timing
            ) {
                dispatchRequest = true;
            }

            deliverResult = !dispatchRequest;

            if (mTag.error == 0 && mBuilder.isLoadCacheAnyway()) {
                deliverResult = true;
                mTag.loadFinished = false;
            }
        }

        //            if (mTag.error == 0 || contentChanged) {
        //                if ((mBuilder.isLoadCacheAnyway() && !noCache)) {
        //                    dispatchRequest = true;
        //                }
        //
        //                deliverResult = !dispatchRequest;
        //                if (mBuilder.isLoadCacheAnyway() && contentChanged) {
        //                    deliverResult = true;
        //                }
        //            }
        //
        //            if (mTag.error != 0 && !contentChanged) {
        //                dispatchRequest = true;
        //            }
    } else {
        dispatchRequest = true;
    }

    if (dispatchRequest) {
        if (!mCallback.willDispatch(mBuilder)) {
            HttpCacheConfiguration configure = HttpCacheConfiguration.configure(mContext);

            Intent service = new Intent();
            service.setAction(configure.action);
            service.putExtra("local", mBuilder.localUri());
            service.putExtra("remote", mBuilder.remoteUri());
            service.putExtra("cache", mBuilder.cacheExpiry());
            service.putExtra("timeout", mBuilder.timeout());
            service.putExtra("params", mBuilder.params());
            service.putExtra("method", mBuilder.method());
            service.putExtra("token", mBuilder.token());

            //Intent serviceIntent = new Intent(mContext,HttpCacheConfiguration.class);
            //mContext.startService(serviceIntent);

            Intent s = createExplicitFromImplicitIntent(mContext, service);
            IntentUtils.describe("devug", s);
            mContext.startService(s);
        }
    }

    return deliverResult;
}

From source file:com.mono.applink.Facebook.java

/** Called when the activity is first created. */
@Override//from  w w  w. j  a  v a  2  s.c  o m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    context = this;

    final String url = getIntent().getData().toString();

    if (url.contains("posts") || url.contains("profile.php")
            || (!url.contains("&") && !url.contains("=") && url.length() > 24))
    //1)Posts->It is impossible to launch FeedbackActivity because of permission denied.
    //With root permission and "am start" it's impossible to pass a Long extra_key...
    //2)Profile
    //3)Nickname
    {
        new FacebookUser().execute();
    } else if (url.contains("sk=inbox"))//Message
    {
        new FacebookMessage().execute();
    } else if (url.contains("event.php"))//event
    {
        new FacebookEvent().execute();
    } else {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Sorry, but this type of link is not currently supported");
        builder.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });
        builder.setPositiveButton("Open in Browser", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                Intent i = new Intent();
                i.setAction("android.intent.action.VIEW");
                i.addCategory("android.intent.category.BROWSABLE");
                i.setComponent(new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"));
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.setData(Uri.parse(url));
                startActivity(i);
                finish();
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }
}

From source file:com.tcity.android.sync.SyncService.java

private void notify(@NotNull String buildConfigurationId, @NotNull String parentProjectId, int size) {
    Notification.Builder builder = new Notification.Builder(this);

    String title = size + " new build" + (size == 1 ? "" : "s");
    String projectName = myDB.getProjectName(parentProjectId);
    String buildConfigurationName = myDB.getBuildConfigurationName(buildConfigurationId);

    Intent activityIntent = new Intent(this, BuildConfigurationOverviewActivity.class);
    activityIntent.putExtra(BuildConfigurationOverviewActivity.ID_INTENT_KEY, buildConfigurationId);
    activityIntent.setAction(Long.toString(System.currentTimeMillis()));

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, activityIntent, 0);

    //noinspection deprecation
    Notification notification = builder.setSmallIcon(R.drawable.ic_launcher).setContentTitle(title)
            .setContentText(projectName + " - " + buildConfigurationName).setContentIntent(contentIntent)
            .setAutoCancel(true).getNotification();

    myManager.notify(buildConfigurationId.hashCode(), notification);
}

From source file:com.pulp.campaigntracker.gcm.GcmIntentService.java

@SuppressWarnings("unchecked")
private void sendNotification(GCM msg) {

    if (msg != null) {

        int index = 1;

        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
        bigText.bigText(msg.getMessage());
        bigText.setBigContentTitle(msg.getTitle());

        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        mNotificationCount = mAppPref.getInt("Notif_Number_Constant", 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notification_app_icon).setContentTitle(msg.getTitle())
                .setStyle(bigText).setContentText(msg.getMessage()).setSound(uri)
                .setNumber(mNotificationCount + 1);

        mAppPref.edit().putInt("Notif_Number_Constant", (mNotificationCount + 1)).commit();

        try {/*from   ww w.  j a  v a  2s.c o m*/
            if ((ArrayList<UserNotification>) ObjectSerializer
                    .deserialize(mAppPref.getString(ConstantUtils.NOTIFICATION, "")) == null) {
                notifyList = new ArrayList<UserNotification>();
            } else {
                notifyList = (ArrayList<UserNotification>) ObjectSerializer
                        .deserialize(mAppPref.getString(ConstantUtils.NOTIFICATION, ""));
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        notification = new UserNotification();
        notification.setTitle(msg.getTitle());
        notification.setMessage(msg.getMessage());
        notification.setNotifyTime(System.currentTimeMillis());
        notifyList.add(notification);

        try {
            mAppPref.edit().putString(ConstantUtils.NOTIFICATION, ObjectSerializer.serialize(notifyList))
                    .commit();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Intent newIntent = null;

        ConstantUtils.SYNC_INTERVAL = 30 * 60 * 1000;

        //         if (mAppPref.getString(ConstantUtils.USER_ROLE, "")
        //               .equals(LoginData.)) {
        //            newIntent = new Intent(getBaseContext(),
        //                  UserMotherActivity.class);
        //            Intent i = new Intent(this, PeriodicService.class);
        //            this.startService(i);

        //         } else {
        newIntent = new Intent(getBaseContext(), SplashScreen.class);
        Intent i = new Intent(this, PeriodicService.class);
        this.startService(i);

        //         }

        PendingIntent contentIntent = PendingIntent.getActivity(GcmIntentService.this, 0, newIntent, 0);
        mBuilder.setAutoCancel(true);
        mBuilder.setContentIntent(contentIntent);

        mNotificationManager.notify(index, mBuilder.build());
        Intent intent = new Intent();
        intent.setAction("googleCloudMessage");
        sendBroadcast(intent);

    }
}

From source file:com.google.developers.actions.debugger.MainActivity.java

public void askCayley(final String query) {
    new AsyncTask<Void, Void, String>() {
        @Override//from  ww w  . j av  a2s .c  o  m
        protected String doInBackground(Void... voids) {
            try {
                // Create a new HttpClient and Post Header
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(Utils.CAYLEY_URL);
                String queryString = WordUtils.capitalize(query);
                String cayleyReq = "function getActionForArtists(artist) {\n"
                        + "  return artist.In(\"http://schema.org/sameAs\").Out(\"http://schema.org/potentialAction\").Has(\"a\", \"http://schema.org/ListenAction\").Out(\"http://schema.org/target\")\n"
                        + "}\n" + "\n" + "function getIdFor(thing) {\n"
                        + "  return g.V(thing).In([\"http://rdf.freebase.com/ns/type.object.name\", \"http://schema.org/name\"]).ToValue()\n"
                        + "}\n" + "\n" + "function getTypeFor(id) {\n"
                        + "  return g.V(id).Out(\"a\").ToValue()\n" + "}\n" + "\n"
                        + "function getActionForName(name) {\n" + "  var uri = getIdFor(name)\n"
                        + "  if (uri == null) {\n" + "    return\n" + "  }\n" + "  var type = getTypeFor(uri)\n"
                        + "  var artist_query\n"
                        + "  if (type == \"http://rdf.freebase.com/ns/music.genre\") {\n"
                        + "    artist_query = g.V(uri).In(\"http://rdf.freebase.com/ns/music.artist.genre\")\n"
                        + "  } else {\n" + "    artist_query = g.V(uri)\n" + "  }\n"
                        + "  return getActionForArtists(artist_query)\n" + "}\n" + "\n" + "getActionForName(\""
                        + queryString + "\").All()";
                httppost.setEntity(new StringEntity(cayleyReq));
                // Execute HTTP Post Request
                HttpResponse httpResponse = httpclient.execute(httppost);
                String response = EntityUtils.toString(httpResponse.getEntity());

                Gson gson = new Gson();
                CayleyResult cayleyResult = gson.fromJson(response, CayleyResult.class);
                if (cayleyResult.isEmpty()) {
                    Utils.showError(MainActivity.this, "No nodes found for " + queryString + " in Cayley.");
                    return null;
                }
                return cayleyResult.getResult(0).getId();
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
            return null;
        }

        @Override
        protected void onPostExecute(String appId) {
            setProgressBarIndeterminateVisibility(false);

            if (appId == null) {
                return;
            }

            Intent intent = new Intent();
            intent.setAction("android.media.action.MEDIA_PLAY_FROM_SEARCH");
            intent.setData(Uri.parse(Utils.convertGSAtoUri(appId)));
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Utils.showError(MainActivity.this, appId + "Activity not found");
            }
        }

    }.execute((Void) null);
}

From source file:com.digitalarx.android.files.FileOperationsHelper.java

public void syncFile(OCFile file) {
    // Sync file//from  w w w  . j  a va  2 s  .  c  om
    Intent service = new Intent(mFileActivity, OperationsService.class);
    service.setAction(OperationsService.ACTION_SYNC_FILE);
    service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
    service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
    service.putExtra(OperationsService.EXTRA_SYNC_FILE_CONTENTS, true);
    mWaitingForOpId = mFileActivity.getOperationsServiceBinder().newOperation(service);

    mFileActivity.showLoadingDialog();
}