Java Code Examples for android.content.Intent

The following are top voted examples for showing how to use android.content.Intent. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: nfc-smime   File: MainActivity.java View source code 8 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    fromText = (TextView) findViewById(R.id.from_text);
    toText = (EditText) findViewById(R.id.to_text);
    toText.setText(DEFAULT_RECIPIENT);
    subjectText = (EditText) findViewById(R.id.subject_text);
    bodyText = (EditText) findViewById(R.id.body_text);
    messageText = (TextView) findViewById(R.id.message);

    sendMailButton = (Button) findViewById(R.id.send_mail_button);
    sendMailButton.setOnClickListener(this);
    importPkcs12Button = (Button) findViewById(R.id.import_pkcs12_button);
    importPkcs12Button.setOnClickListener(this);
    nfcSignButton = (Button) findViewById(R.id.send_mail_nfc_button);
    nfcSignButton.setOnClickListener(this);
    nfcSignButton.setEnabled(false);

    adapter = NfcAdapter.getDefaultAdapter(this);

    pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
            getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    IntentFilter techDiscovered = new IntentFilter(
            NfcAdapter.ACTION_TECH_DISCOVERED);
    filters = new IntentFilter[] { techDiscovered };
    techLists = new String[][] { new String[] { IsoDep.class.getName() } };

    tryLoadFromKeyStore();
}
 
Example 2
Project: property-db   File: RecentApplicationsDialog.java View source code 8 votes vote down vote up
private void switchTo(RecentTag tag) {
    if (tag.info.id >= 0) {
        // This is an active task; it should just go to the foreground.
        final ActivityManager am = (ActivityManager)
                getContext().getSystemService(Context.ACTIVITY_SERVICE);
        am.moveTaskToFront(tag.info.id, ActivityManager.MOVE_TASK_WITH_HOME);
    } else if (tag.intent != null) {
        tag.intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
                | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
        try {
            getContext().startActivity(tag.intent);
        } catch (ActivityNotFoundException e) {
            Log.w("Recent", "Unable to launch recent task", e);
        }
    }
}
 
Example 3
Project: sawan-bar   File: OtaUtils.java View source code 7 votes vote down vote up
/**
 * When SPC notice times out, force phone to power down.
 */
public void onOtaCloseSpcNotice() {
    if (DBG) log("onOtaCloseSpcNotice(), send shutdown intent");
    Intent shutdown = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
    shutdown.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
    shutdown.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    mContext.startActivity(shutdown);
}
 
Example 4
Project: packages_apps_Mms   File: MessageStatusReceiver.java View source code 7 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (MESSAGE_STATUS_RECEIVED_ACTION.equals(intent.getAction())) {

        Uri messageUri = intent.getData();
        byte[] pdu = (byte[]) intent.getExtra("pdu");
        String format = intent.getStringExtra("format");

        SmsMessage message = updateMessageStatus(context, messageUri, pdu, format);

        // Called on the UI thread so don't block.
        if (message != null && message.getStatus() < Sms.STATUS_PENDING)
            MessagingNotification.nonBlockingUpdateNewMessageIndicator(context,
                    true, message.isStatusReportMessage());
   }
}
 
Example 5
Project: Trigger   File: IdleStatusController.java View source code 7 votes vote down vote up
public IdlenessTracker() {
    mAlarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent intent = new Intent(ACTION_TRIGGER_IDLE)
            .setPackage("android")
            .setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
    mIdleTriggerIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    // At boot we presume that the user has just "interacted" with the
    // device in some meaningful way.
    mIdle = false;
}
 
Example 6
Project: MobileSensing   File: TimeChangeListener.java View source code 7 votes vote down vote up
@Override
public void onReceive( Context context, Intent intent )
{
  final String action = intent.getAction();
  if ( Intent.ACTION_DATE_CHANGED.equals( action ) ||
      Intent.ACTION_TIME_CHANGED.equals( action ) )
  {
    Logger.getInstance().debug(
        this, "Date/time change was signaled by system" );
    
    TimeProvider.getInstance().asynchronousUpdateTime( context.getApplicationContext() );      
  }
}
 
Example 7
Project: BLEConnect   File: DeviceScanActivity.java View source code 6 votes vote down vote up
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
    if (device == null) return;
    final Intent intent = new Intent(this, DeviceControlActivity.class);
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
    intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
    if (mScanning) {
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        mScanning = false;
    }
    startActivity(intent);
}
 
Example 8
Project: dlna   File: StartMp3Activity.java View source code 6 votes vote down vote up
public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.music_player_layout);
		Intent intent = getIntent();
		url = intent.getStringExtra("URL");
		
		mMediaPlayer = new MediaPlayer();
		mStart = (ImageButton) findViewById(R.id.btn_play);
		mPause = (ImageButton) findViewById(R.id.btn_pause);
//		mNext = (Button) findViewById(R.id.play_next);
//		mBefore = (Button) findViewById(R.id.play_before);
//		mStop = (Button) findViewById(R.id.play_stop);
//		// mImageView = (ImageView) findViewById(R.id.mImageView);
//		mTextView = (TextView) findViewById(R.id.mText);
		mTextView = (TextView)findViewById(R.id.title);
		
		seeker = (SeekBar)findViewById(R.id.playback_seeker);
		
		seeker.setVisibility(View.GONE);
		totaltime = (TextView)findViewById(R.id.tv_totalTime);
		currentime = (TextView)findViewById(R.id.tv_curTime);
		totaltime.setVisibility(View.GONE);
		currentime.setVisibility(View.GONE);
		
		TextView tv = (TextView) findViewById(R.id.title);
		tv.setVisibility(View.GONE);
		
		TextView content = (TextView) findViewById(R.id.content);
		content.setText(url);
		
		mStart.setOnClickListener(mStartOnClickListener);
		mPause.setOnClickListener(mPauseOnClickListener);
//		mStop.setOnClickListener(mStopOnClickListener);

		mMediaPlayer.setOnCompletionListener(mOnCompletionListener);
		mMediaPlayer.setOnErrorListener(mErrorListener);
		
		
	}
 
Example 9
Project: dlna   File: YouUtility.java View source code 6 votes vote down vote up
public static void switchLinkType(Context context, Intent intent,
	String weibourl, String ourl, String url, Boolean showPlayButton,
	String definition, String pic, String linkType, String name,
	String desc) {
   switch (Integer.parseInt(linkType)) {
    case 0: // fullplayer
    	LOG.v(TAG,"switchLinkType","fullplayer");
    	intent.setAction(YouPlayerConstant.YOU_ACTION_FULLPLAY);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_URL,url);
    	//skipIntent.putExtra(Constant.ACTION_PAGE, fn_Core.FN_PAGE_FULL_SCREEN_PLAYER);
    	break;
    case 3:  //open webview
    	LOG.v(TAG,"switchLinkType","open webview");
    	 intent.setAction("android.intent.action.VIEW");
    	 Uri content_url1 = Uri.parse(url);   
 		 intent.setData(content_url1);
 		 if (android.os.Build.VERSION.SDK_INT < 16) { 
 			 intent.setClassName("com.android.browser","com.android.browser.BrowserActivity"); 
 		 } 
    	 break;

    case 8: // original web
    	LOG.v(TAG,"switchLinkType","original web");
    	intent.setAction(YouPlayerConstant.YOU_ACTION_NOTIFICATION);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_PAGE, You_Core.FN_PAGE_ONLINE_WEB_DETAIL);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_WEIBOURL,weibourl);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_OURL,ourl);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_URL,url);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_BTNPLY,showPlayButton);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_DEFINITION,definition);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_PIC,pic);
    	intent.putExtra(YouPlayerConstant.YOU_ACTION_NAME,name);
    	break;	 
   default:
	  break;
}
  }
 
Example 10
Project: arduino-android   File: DroidTempLoggerLaunch.java View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);

	Intent intent = createIntent(this);

	intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
			| Intent.FLAG_ACTIVITY_CLEAR_TOP);
	try {
		startActivity(intent);
	} catch (ActivityNotFoundException e) {
		Log.e(TAG, "unable to start activity", e);
	}
	finish();
}
 
Example 11
Project: aws-toolkit-eclipse   File: S3UploaderActivity.java View source code 6 votes vote down vote up
protected void onPostExecute(S3TaskResult result) {
	
	if (result.getErrorMessage() != null) {

		displayErrorAlert(
				S3UploaderActivity.this
						.getString(R.string.browser_failure_title),
				result.getErrorMessage());
	} else if (result.getUri() != null) {

		// Display in Browser.
		startActivity(new Intent(Intent.ACTION_VIEW, result.getUri()));
	}
}
 
Example 12
Project: arduino-android   File: OpenAccessoryTest.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();
  if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
    UsbAccessory accessory = UsbManager.getAccessory(intent);
    if (accessory != null && accessory.equals(mAccessory)) {
      log("Detached");
      closeAccessory();
    }
  }
}
 
Example 13
Project: my-ministry-assistant   File: SummaryFragment.java View source code 6 votes vote down vote up
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
		case R.id.summary_send_report:
			Intent share = new Intent(android.content.Intent.ACTION_SEND);
    		share.setType("text/plain");
    		share.setFlags((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); 
    		share.putExtra(android.content.Intent.EXTRA_TEXT, populateShareString());
    		share.putExtra(android.content.Intent.EXTRA_SUBJECT, buttonFormat.format(monthPicked.getTime()).toString() + " " + monthPicked.get(Calendar.YEAR));
    		startActivity(Intent.createChooser(share, getResources().getString(R.string.menu_send_report)));
        	
    		return true;
        	
		case R.id.summary_add_item:
			((MainActivity)getActivity()).goToNavDrawerItem(MainActivity.TIME_ENTRY_ID);
			
			return true;
	}
	
	return super.onOptionsItemSelected(item);
}
 
Example 14
Project: dlna   File: YouPhonePowerUtil.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	String action = intent.getAction();
	if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {

		int level = intent.getIntExtra("level", 0);
		int scale = intent.getIntExtra("scale", POWER_SCALE);
		if(phonePowerListener != null)
			phonePowerListener.powerChange(level, scale);
	}

}
 
Example 15
Project: dlna   File: ContentActivity.java View source code 6 votes vote down vote up
private void goPicturePlayerActivity(int position, Item item) {

				int position1=-1;
                   List<Item> newlist = new ArrayList<Item>();
			for (int i = 0; i < mCurItems.size(); i++) {
				Item item1 = mCurItems.get(i);
			
					if (UpnpUtil.isPictureItem(item1)) {
						newlist.add(item1);
						if(i<=position) {
							position1++;
						}
					}
				}
		//MediaManager.getInstance().setPictureList(mCurItems);
		MediaManager.getInstance().setPictureList(newlist);
		
		Intent intent = new Intent();
		intent.setClass(this, PicturePlayerActivity.class);
		intent.putExtra(PicturePlayerActivity.PLAY_INDEX, position1);
		ItemFactory.putItemToIntent(item, intent);
		ContentActivity.this.startActivity(intent);
	}
 
Example 16
Project: Gui2Go   File: EditorActivity.java View source code 6 votes vote down vote up
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // Grab info from the intent
    refreshProjectData(true);
    Bundle data = intent.getExtras();
    projectInfo = data.getParcelable("project");
    activityInfo = data.getParcelable("activity");
    this.setTitle(projectInfo.name + " - ");
    if (data.getBoolean("projectLoaderFlag")) {
        // if this activity is loaded from the project loader
        // we need to load the correct layout XML
        LoadXML(projectInfo.name, activityInfo.name);
    }
    if (data.getBoolean("isNewActivity")) {
        saveActivityXML(false);
    }

    // set the correct size
    setScreenSize(activityInfo.screenSize);

    ActionBar actionBar = getActionBar();
    int position = 0;
    for (int i = 0; i < activityList.size(); i++) {
        if (activityList.get(i).name.equals(activityInfo.name)) {
            position = i;
        }
    }
    actionBar.setSelectedNavigationItem(position);
}
 
Example 17
Project: phonegap-geolocation   File: CordovaChromeClient.java View source code 6 votes vote down vote up
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
{
    mUploadMessage = uploadMsg;
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.addCategory(Intent.CATEGORY_OPENABLE);
    i.setType("*/*");
    this.cordova.getActivity().startActivityForResult(Intent.createChooser(i, "File Browser"),
            FILECHOOSER_RESULTCODE);
}
 
Example 18
Project: widgets   File: PickAppWidgets.java View source code 6 votes vote down vote up
private void configureWidget(Intent data) {
    Bundle extras = data.getExtras();
    int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
    AppWidgetProviderInfo appWidgetInfo =
            mAppWidgetManager.getAppWidgetInfo(appWidgetId);
    if (appWidgetInfo.configure != null) {
        Intent intent =
                new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
        intent.setComponent(appWidgetInfo.configure);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
    } else {
        smAppWidgetHost = mAppWidgetHost;
        smAppWidgetManager = mAppWidgetManager;
        widget = data;
        if(widget == null) Log.e("Floating Widgets","Fasten seat belts and prepare for crash");
        StandOutWindow.show(this,FloatingWidget.class,++id);
        finish();
    }
}
 
Example 19
Project: arduino-android   File: InputController.java View source code 6 votes vote down vote up
public void openSettings()
{
	Bundle bundle = new Bundle();
	bundle.putLong("index", new Long(index));
	Intent newIntent = new Intent(mHostActivity, SettingsActivity.class);
	newIntent.putExtras(bundle);
	mHostActivity.startActivityForResult(newIntent, 0);
}
 
Example 20
Project: aws-toolkit-eclipse   File: S3UploaderActivity.java View source code 6 votes vote down vote up
protected void onActivityResult(int requestCode, int resultCode,
		Intent imageReturnedIntent) {
	super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

	switch (requestCode) {
	case PHOTO_SELECTED:
		if (resultCode == RESULT_OK) {

			Uri selectedImage = imageReturnedIntent.getData();
			new S3PutObjectTask().execute(selectedImage);
		}
	}
}
 
Example 21
Project: nfc-smime   File: MainActivity.java View source code 6 votes vote down vote up
@Override
protected void onNewIntent(Intent intent) {
    Log.d(TAG, "Intent: " + intent);

    setIntent(intent);

    try {
        if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())
                || NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent
                        .getAction())) {
            Tag tagFromIntent = intent
                    .getParcelableExtra(NfcAdapter.EXTRA_TAG);
            messageText.setText("Found NFC tag: ");
            Log.d(TAG, "Suported techs: ");
            for (String tech : tagFromIntent.getTechList()) {
                Log.d(TAG, "\t" + tech);
                messageText.append(tech.replaceAll("android.nfc.", "")
                        + " ");
            }
            messageText.append("\n");

            IsoDep tag = IsoDep.get(tagFromIntent);
            if (tag == null) {
                Log.w(TAG, "Not an IsoDep tag: " + tagFromIntent);
                return;
            }

            tag.connect();
            msc = new MuscleCard(tag);

            try {
                msc.select();

                messageText.append("Found MuscleCard");
                nfcSignButton.setEnabled(true);
            } finally {
                if (tag != null) {
                    tag.close();
                }
            }

        }
    } catch (Exception e) {
        Log.e(TAG, "Error: " + e.getMessage(), e);
        Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG)
                .show();
    }
}
 
Example 22
Project: dlna   File: DeviceChangeBrocastReceiver.java View source code 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
	String action = intent.getAction();

	
	if (DeviceBrocastFactory.ADD_DEVICES.equalsIgnoreCase(action) || 
			DeviceBrocastFactory.REMOVE_DEVICES.equalsIgnoreCase(action) || 
			DeviceBrocastFactory.CLEAR_DEVICES.equalsIgnoreCase(action)){			
		boolean isSelDeviceChange = intent.getBooleanExtra(DeviceBrocastFactory.REMOVE_EXTRA_FLAG, false);
		if (mListener != null){
			mListener.onDeviceChange(isSelDeviceChange);
		}
	}

}
 
Example 23
Project: phonegap-geolocation   File: App.java View source code 6 votes vote down vote up
/**
 * Listen for telephony events: RINGING, OFFHOOK and IDLE
 * Send these events to all plugins using
 *      CordovaActivity.onMessage("telephone", "ringing" | "offhook" | "idle")
 */
private void initTelephonyReceiver() {
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    //final CordovaInterface mycordova = this.cordova;
    this.telephonyReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            // If state has changed
            if ((intent != null) && intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
                if (intent.hasExtra(TelephonyManager.EXTRA_STATE)) {
                    String extraData = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                    if (extraData.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                        LOG.i(TAG, "Telephone RINGING");
                        webView.postMessage("telephone", "ringing");
                    }
                    else if (extraData.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                        LOG.i(TAG, "Telephone OFFHOOK");
                        webView.postMessage("telephone", "offhook");
                    }
                    else if (extraData.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                        LOG.i(TAG, "Telephone IDLE");
                        webView.postMessage("telephone", "idle");
                    }
                }
            }
        }
    };

    // Register the receiver
    this.cordova.getActivity().registerReceiver(this.telephonyReceiver, intentFilter);
}
 
Example 24
Project: dlna   File: IOHelper.java View source code 6 votes vote down vote up
public static  void openFile(Context context, File file) {
		try{

		File myFile = file;
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
//		String type = getMIMEType(myFile.getName());
		String type = getMIMEType(myFile);
		intent.setDataAndType(Uri.fromFile(myFile), type);
		context.startActivity(intent);
		}
		catch(Exception e)
		{
			System.out.print("e=" + e);
		}
	}
 
Example 25
Project: dlna   File: YouUtility.java View source code 6 votes vote down vote up
public static void toShareToSystem(Context context,String imagepath,String url, String shareContent){
LOG.v("youUtility", "toShareToSystem", "imagepath:"+imagepath);   
      Intent intent=new Intent(Intent.ACTION_SEND);
      intent.setType("text/plain");
      if( imagepath != null ){
          
          File f = new File(imagepath);        
          if( f.exists() ){
              intent.setType("image/png");
              Uri u = Uri.fromFile(f);
              intent.putExtra(Intent.EXTRA_STREAM, u);
          }
      }
       intent.putExtra(Intent.EXTRA_SUBJECT, context.getResources().getText(R.string.share_blog_title));
       if( url == null ) url = "";
       String shareText = context.getResources().getText(R.string.share_text_start).toString();
       shareText += (shareContent == null ? "" : shareContent); 
       intent.putExtra(Intent.EXTRA_TEXT, shareText +"\n"+ url);
       intent.putExtra("sms_body", shareText +"\n"+ url);
       context.startActivity(Intent.createChooser(intent, context.getResources().getText(R.string.share_blog_title)));
}
 
Example 26
Project: MyDownload   File: DownloadPage.java View source code 6 votes vote down vote up
/**
 * Open or delete content where the download db cursor currently is.  Sends
 * an Intent to perform the action.
 * @param delete If true, delete the content.  Otherwise open it.
 */
private void openOrDeleteCurrentDownload(boolean delete) {
    int packageColumnId = mDownloadCursor.getColumnIndexOrThrow(
            Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE);
    String packageName = mDownloadCursor.getString(packageColumnId);
    Intent intent = new Intent(delete ? Intent.ACTION_DELETE
            : Downloads.Impl.ACTION_NOTIFICATION_CLICKED);
    Uri contentUri = ContentUris.withAppendedId(
            Downloads.Impl.CONTENT_URI,
            mDownloadCursor.getLong(mIdColumnId));
    intent.setData(contentUri);
    intent.setPackage(packageName);
    sendBroadcast(intent);
}
 
Example 27
Project: sputnik-sdk-android-demo   File: MenuActivity.java View source code 6 votes vote down vote up
public void onReceive(Context ctxt, Intent intent) {
    // Get the dId of the completed download.
    long dId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
    Cursor c = mgr.query(new DownloadManager.Query().setFilterById(dId));
    int status = DownloadManager.STATUS_FAILED;
    if(c.moveToFirst())
        status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
    String zipPath = Sputnik.getWorkDir() +
            downloadData_.get(dId);
    if(status == DownloadManager.STATUS_SUCCESSFUL) {
        Toast.makeText(ctxt, getString(R.string.downloadComplete), Toast.LENGTH_LONG).show();
        if(downloadData_.containsKey(dId)) {
            String destPath = Sputnik.getWorkDir();
            new UnzipTask(MenuActivity.this).execute(downloadData_.get(dId), zipPath, destPath, "true");
        } else
            Log.e("UnzipTask", dId +" not found in downloads");
    } else {
        Toast.makeText(ctxt, getString(R.string.downloadFailed), Toast.LENGTH_LONG).show();
        File zipFile = new File(zipPath);
        if(zipFile.exists())
            zipFile.delete();
    }
}
 
Example 28
Project: ExcusePro   File: SearchView.java View source code 6 votes vote down vote up
/**
 * When a particular suggestion has been selected, perform the various lookups required
 * to use the suggestion.  This includes checking the cursor for suggestion-specific data,
 * and/or falling back to the XML for defaults;  It also creates REST style Uri data when
 * the suggestion includes a data id.
 *
 * @param c The suggestions cursor, moved to the row of the user's selection
 * @param actionKey The key code of the action key that was pressed,
 *        or [email protected] KeyEvent#KEYCODE_UNKNOWN} if none.
 * @param actionMsg The message for the action key that was pressed,
 *        or <code>null</code> if none.
 * @return An intent for the suggestion at the cursor's position.
 */
private Intent createIntentFromSuggestion(Cursor c, int actionKey, String actionMsg) {
    try {
        // use specific action if supplied, or default action if supplied, or fixed default
        String action = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_ACTION);

        if (action == null) {
            action = mSearchable.getSuggestIntentAction();
        }
        if (action == null) {
            action = Intent.ACTION_SEARCH;
        }

        // use specific data if supplied, or default data if supplied
        String data = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA);
        if (data == null) {
            data = mSearchable.getSuggestIntentData();
        }
        // then, if an ID was provided, append it.
        if (data != null) {
            String id = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID);
            if (id != null) {
                data = data + "/" + Uri.encode(id);
            }
        }
        Uri dataUri = (data == null) ? null : Uri.parse(data);

        String query = getColumnString(c, SearchManager.SUGGEST_COLUMN_QUERY);
        String extraData = getColumnString(c, SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA);

        return createIntent(action, dataUri, extraData, query, actionKey, actionMsg);
    } catch (RuntimeException e ) {
        int rowNum;
        try {                       // be really paranoid now
            rowNum = c.getPosition();
        } catch (RuntimeException e2 ) {
            rowNum = -1;
        }
        Log.w(LOG_TAG, "Search suggestions cursor at row " + rowNum +
                        " returned exception.", e);
        return null;
    }
}
 
Example 29
Project: BioWiki   File: MediaUtils.java View source code 6 votes vote down vote up
public static void launchPictureLibrary(Fragment fragment) {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);

    AppLockManager.getInstance().setExtendedTimeout();
    fragment.startActivityForResult(Intent.createChooser(intent, fragment.getString(R.string.pick_photo)), RequestCode.ACTIVITY_REQUEST_CODE_PICTURE_LIBRARY);
}
 
Example 30
Project: PTM-OSMGeotrigger   File: OsmTriggerActivity.java View source code 6 votes vote down vote up
/**
 * Handle new intent events.
 */
@Override
protected void onNewIntent(Intent intent) {
	String method = intent.getStringExtra("Method");
	if(method != null && method.equals(METHOD_NOTIFICATION)){
		// notification item was pressed
		selectItem(0);
		Bundle data = intent.getBundleExtra("Data");
		showNotificationDetails(data);
	}
}
 
Example 31
Project: TrustedIntents   File: TrustedIntents.java View source code 6 votes vote down vote up
private boolean isIntentSane(Intent intent) {
    if (intent == null)
        return false;
    if (TextUtils.isEmpty(intent.getPackage())) {
        ComponentName componentName = intent.getComponent();
        if (componentName == null || TextUtils.isEmpty(componentName.getPackageName())) {
            return false;
        }
    }
    return true;
}
 
Example 32
Project: SpendingTracker   File: SettingActivity.java View source code 6 votes vote down vote up
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    switch (i){
        case FEEDBACK:
            Intent email = new Intent(Intent.ACTION_SENDTO);
            email.setType(HTTP.PLAIN_TEXT_TYPE);
            email.setData(Uri.parse("mailto:[email protected]"));
            email.putExtra(Intent.EXTRA_SUBJECT, "Spending Tracker Feedback");
            try {
                startActivity(Intent.createChooser(email, "Send Feedback:"));
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(view.getContext(), "There are no email clients installed.", Toast.LENGTH_SHORT).show();
            }
            break;
        case HELP:
            FragmentManager fm = getSupportFragmentManager();
            InfoDialogFragment fragment = new InfoDialogFragment();
            fragment.show(fm, "InfoFragment");
            break;
    }
}
 
Example 33
Project: BioWiki   File: MediaGalleryActivity.java View source code 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MediaGalleryPickerActivity.REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            ArrayList<String> ids = data.getStringArrayListExtra(MediaGalleryPickerActivity.RESULT_IDS);
            mMediaGalleryEditFragment.setMediaIds(ids);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 34
Project: sputnik-sdk-android-demo   File: MenuActivity.java View source code 6 votes vote down vote up
/**
 * @param item
 * @return
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch (id) {
        case R.id.action_about:
            Uri webpage = Uri.parse(getString(R.string.sputnik_url));
            Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
 
Example 35
Project: weather-notification-android   File: WeatherNotificationManagerTest.java View source code 6 votes vote down vote up
public void testCreateIntentDisableNotification() {
    Intent intent = WeatherNotificationManager.createIntent(false, null);
    Parcel parcel = Parcel.obtain();
    intent.writeToParcel(parcel, 0);
    parcel.setDataPosition(0);
    intent.readFromParcel(parcel);
    assertTrue(intent.hasExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION));
    assertFalse(intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, true));
    assertFalse(intent.hasExtra(IntentParameters.EXTRA_WEATHER));
}
 
Example 36
Project: Pure-File-Manager   File: IntentsActionPolicy.java View source code 6 votes vote down vote up
/**
 * Creates a chooser intent to share the files
 *
 * @param ctx          The current context
 * @param genericFiles The file system objects
 * @return chooser intent or null if no application to handle
 */
@Nullable
public static Intent createShareIntent(
        @NonNull final Context ctx,
        @NonNull final List<GenericFile> genericFiles) {
    try {
        // Create the intent to
        final Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_SEND_MULTIPLE);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

        // Create an array list of the uris to send
        final int cc = genericFiles.size();
        final ArrayList<Uri> uris = new ArrayList<>(cc);
        String lastMimeType = null;
        boolean sameMimeType = true;
        for (final GenericFile fso : genericFiles) {

            // Folders are not allowed
            if (fso.isDirectory()) continue;

            // Check if we can use a unique mime/type
            String mimeType = MimeTypes.getMimeType(fso.toFile());
            if (mimeType == null) {
                sameMimeType = false;
            } else if (sameMimeType &&
                    (lastMimeType != null &&
                            mimeType.compareTo(lastMimeType) != 0)) {
                sameMimeType = false;
            }
            lastMimeType = mimeType;

            // Add the uri
            uris.add(getUriFromFile(ctx, fso.toFile()));
        }
        if (sameMimeType) {
            intent.setType(lastMimeType);
        } else {
            intent.setType(MimeTypes.ALL_MIME_TYPES);
        }
        intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);

        // Resolve the intent
        return resolveIntent(ctx, intent);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 37
Project: p1keyboard   File: BluezIMESettings.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	if (DRIVER_NAMES == null) {
		
		DRIVER_NAMES = intent.getStringArrayExtra(BluezService.EVENT_REPORT_CONFIG_DRIVER_NAMES);
		DRIVER_DISPLAYNAMES = intent.getStringArrayExtra(BluezService.EVENT_REPORT_CONFIG_DRIVER_DISPLAYNAMES);
		
    	CharSequence[] entries = new CharSequence[DRIVER_NAMES.length];
    	CharSequence[] entryValues = new CharSequence[entries.length];
    	String[] displayNames = BluezIMESettings.this.getResources().getStringArray(R.array.driver_displaynames);
    	
    	for(int i = 0; i < entries.length; i++) {
    		if (displayNames.length > i)
    			entries[i] = displayNames[i];
    		else
    			entries[i] = DRIVER_DISPLAYNAMES[i];
    		
    		entryValues[i] = DRIVER_NAMES[i];
    	}
    	
    	for(ListPreference p : m_drivers) {
    		p.setEntries(entries);
    		p.setEntryValues(entryValues);
    		p.setEnabled(true);
    	}
    	
    	BluezIMESettings.this.updateDisplay();
	}
}
 
Example 38
Project: flow-android   File: MainFlowActivity.java View source code 6 votes vote down vote up
private void handleNfcIntent(Intent intent) {
    if (intent == null) return;

    // Check if Activity was opened via NFC to load a specific Fragment
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {

        String payload = intent.getDataString();

        if (payload != null) {

            String profileUrlFormat = Constants.BASE_URL + Constants.URL_PROFILE_EXT;
            String courseUrlFormat = Constants.BASE_URL + Constants.URL_COURSE_EXT;

            if (payload.startsWith(profileUrlFormat)) {
                // Open a ProfileFragment with the provided payload profile ID

                String profileID = payload.substring(profileUrlFormat.length());
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.content_frame, ProfileFragment.newInstance(profileID))
                        .addToBackStack(null)
                        .commit();
            } else if (payload.startsWith(courseUrlFormat)) {
                // Open a CourseFragment with the provided payload course ID

                String courseID = payload.substring(courseUrlFormat.length());
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.content_frame, CourseFragment.newInstance(courseID))
                        .addToBackStack(null)
                        .commit();
            }

            JSONObject properties = new JSONObject();
            try {
                properties.put("uri", payload);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            ((FlowApplication) getApplication()).track("NFC receive event", properties);
        }
    }
}
 
Example 39
Project: hacktoolkit-android_lib   File: HTKUtils.java View source code 6 votes vote down vote up
/**
 *
 * @param phoneNumber
 *
 * <uses-permission android:name="android.permission.CALL_PHONE" />
 */
public static void callPhone(Activity currentActivity, String phoneNumber) {
	Intent callIntent = new Intent(Intent.ACTION_CALL);
	callIntent.setData(Uri.parse("tel:" + phoneNumber));
	switchActivity(currentActivity, callIntent);
}
 
Example 40
Project: BioWiki   File: MediaBrowserActivity.java View source code 6 votes vote down vote up
private void uploadSharedFiles() {
    Intent intent = getIntent();
    String action = intent.getAction();
    final List<Uri> multi_stream;
    if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
        multi_stream = intent.getParcelableArrayListExtra((Intent.EXTRA_STREAM));
    } else {
        multi_stream = new ArrayList<Uri>();
        multi_stream.add((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
    }
    mMediaAddFragment.uploadList(multi_stream);

    // clear the intent's action, so that in case the user rotates, we don't re-upload the same
    // files
    getIntent().setAction(null);
}
 
Example 41
Project: BioWiki   File: EditPostContentFragment.java View source code 6 votes vote down vote up
protected void setPostContentFromShareAction() {
    Intent intent = mActivity.getIntent();

    // Check for shared text
    String text = intent.getStringExtra(Intent.EXTRA_TEXT);
    String title = intent.getStringExtra(Intent.EXTRA_SUBJECT);
    if (text != null) {

        if (title != null) {
            mTitleEditText.setText(title);
        }

        if (text.contains("youtube_gdata")) {
            // Just use the URL for YouTube links for oEmbed support
            mContentEditText.setText(text);
        } else {
            // add link tag around URLs, trac #64
            text = text.replaceAll("((http|https|ftp|mailto):\\S+)", "<a href=\"$1\">$1</a>");
            mContentEditText.setText(BWHtml.fromHtml(StringUtils.addPTags(text), getActivity(), mActivity.getPost()));
        }
    }

    // Check for shared media
    if (intent.hasExtra(Intent.EXTRA_STREAM)) {
        String action = intent.getAction();
        String type = intent.getType();
        ArrayList<Uri> sharedUris;

        if (Intent.ACTION_SEND_MULTIPLE.equals(action)) {
            sharedUris = intent.getParcelableArrayListExtra((Intent.EXTRA_STREAM));
        } else {
            // For a single media share, we only allow images and video types
            if (type != null && (type.startsWith("image") || type.startsWith("video"))) {
                sharedUris = new ArrayList<Uri>();
                sharedUris.add((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
            } else {
                return;
            }
        }

        if (sharedUris != null) {
            List<Serializable> params = new Vector<Serializable>();
            params.add(sharedUris);
            params.add(type);
            new processAttachmentsTask().execute(params);
        }
    }
}
 
Example 42
Project: TextSecureSMP   File: PushContactSelectionActivity.java View source code 6 votes vote down vote up
private void handleSelectionFinished() {
  Intent resultIntent = getIntent();
  List<String> selectedContacts = contactsFragment.getSelectedContacts();

  if (selectedContacts != null) {
    resultIntent.putStringArrayListExtra("contacts", new ArrayList<>(selectedContacts));
  }

  setResult(RESULT_OK, resultIntent);
  finish();
}
 
Example 43
Project: feeddroid   File: FolderListActivity.java View source code 6 votes vote down vote up
/**
 * [email protected]}
 */
@Override
public boolean onContextItemSelected(MenuItem item) {
	AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	FolderItemDao backing = ((FolderListRow)info.targetView).getBacking();
	long id = backing.getId();
	switch (item.getItemId()) {
	case EDIT_ID:
		
		if (((FolderListRow)info.targetView).getItemType() == FolderListRow.CHANNEL_VIEW) {
			startActivity(new Intent(Intent.ACTION_EDIT,
					ContentUris.withAppendedId(FeedDroid.Channels.CONTENT_URI, id)));
		}
		return true;
	case DELETE_ID:
		if (((FolderListRow)info.targetView).getItemType() == FolderListRow.CHANNEL_VIEW) {
			removeChannel(id);
		} else if (((FolderListRow)info.targetView).getItemType() == FolderListRow.FOLDER_VIEW) {
			removeFolder(id);
			
			
		}
		return true;
	case MOVE_ID:
		mSelectedRow = info.position;
		showDialog(SHOW_MOVE);
		return true;

	default:
		return false;
	}
}
 
Example 44
Project: AndroidLibraryProject   File: ContextAwareFunction.java View source code 6 votes vote down vote up
/**
 * Description : Method to pause the song. It uses ACTION_MEDIA_BUTTON intent.
 */
public final void pauseSong()
{
	if(CAFConfig.isEnableDebugging())
	{
		Log.d(TAG,"pauseSong Method");
	}	
	try
	{
		mAudioManager = (AudioManager)localContext.getSystemService(Context.AUDIO_SERVICE);
		eventtime = SystemClock.uptimeMillis();
		if(mAudioManager!=null)
		{
			if(mAudioManager.isMusicActive())
			{
				Log.d("PauseSong","Check1");
				Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
				KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE, 0);
				downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
				localContext.sendOrderedBroadcast(downIntent, null);
				Log.d("PauseSong","Check2");
			}
		}
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
}
 
Example 45
Project: financius-public   File: ModelListActivity.java View source code 6 votes vote down vote up
protected void onExtras(Intent extras) {
    mode = (Mode) extras.getSerializableExtra(EXTRA_MODE);
    selectedModels = extras.getParcelableArrayExtra(EXTRA_SELECTED_MODELS);
    if (mode == null) {
        throw new IllegalStateException("Activity " + ((Object) this).getClass().getName() + " must be created with Intent containing " + EXTRA_MODE + " with values from " + Mode.class.getName());
    }
}
 
Example 46
Project: flow-android   File: CalendarHelper.java View source code 6 votes vote down vote up
public static Intent getAddCalenderEventIntent(Exam exam) {
    String courseId = exam.getCourseId();
    String sections = exam.getSections();
    String location = exam.getLocation();
    String startDate = "";
    String endDate = "";
    String startTime = "";
    String endTime = "";

    Intent intent = new Intent(Intent.ACTION_INSERT);
    if (exam.getStartDate() != 0 && exam.getEndDate() != 0) {
        // Missing start/end date. Let's leave this to the user to enter
        startDate = getDateString(new Date(exam.getStartDate()));
        endDate = getDateString(new Date(exam.getEndDate()));
        startTime = getTimeString(new Date(exam.getStartDate()));
        endTime = getTimeString(new Date(exam.getEndDate()));

        // TODO: verify that the format of exam.getStartDate() is appropriate
        intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, exam.getStartDate())
                .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, exam.getEndDate());

    }
    intent.setData(CalendarContract.Events.CONTENT_URI)
            .putExtra(CalendarContract.Events.TITLE,
                    String.format("%s Exam", courseId.toUpperCase()))
            .putExtra(CalendarContract.Events.DESCRIPTION,
                    String.format("Course: %s\nSection: %s\nDate: %s\nTime: %s - %s\nLocation: %s",
                            courseId,
                            sections,
                            startDate,
                            startTime,
                            endTime,
                            location))
            .putExtra(CalendarContract.Events.EVENT_LOCATION, location)
            .putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY);
    return intent;
}
 
Example 47
Project: property-db   File: ServiceRecord.java View source code 6 votes vote down vote up
ServiceRecord(ActivityManagerService ams,
        BatteryStatsImpl.Uid.Pkg.Serv servStats, ComponentName name,
        Intent.FilterComparison intent, ServiceInfo sInfo, Runnable restarter) {
    this.ams = ams;
    this.stats = servStats;
    this.name = name;
    shortName = name.flattenToShortString();
    this.intent = intent;
    serviceInfo = sInfo;
    appInfo = sInfo.applicationInfo;
    packageName = sInfo.applicationInfo.packageName;
    processName = sInfo.processName;
    permission = sInfo.permission;
    baseDir = sInfo.applicationInfo.sourceDir;
    resDir = sInfo.applicationInfo.publicSourceDir;
    dataDir = sInfo.applicationInfo.dataDir;
    exported = sInfo.exported;
    this.restarter = restarter;
    createTime = SystemClock.elapsedRealtime();
    lastActivity = SystemClock.uptimeMillis();
    userId = UserHandle.getUserId(appInfo.uid);
}
 
Example 48
Project: property-db   File: ActivityManagerService.java View source code 6 votes vote down vote up
public int startActivityIntentSender(IApplicationThread caller,
        IntentSender intent, Intent fillInIntent, String resolvedType,
        IBinder resultTo, String resultWho, int requestCode,
        int flagsMask, int flagsValues, Bundle options) {
    enforceNotIsolatedCaller("startActivityIntentSender");
    // Refuse possible leaked file descriptors
    if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
        throw new IllegalArgumentException("File descriptors passed in Intent");
    }
    
    IIntentSender sender = intent.getTarget();
    if (!(sender instanceof PendingIntentRecord)) {
        throw new IllegalArgumentException("Bad PendingIntent object");
    }
    
    PendingIntentRecord pir = (PendingIntentRecord)sender;
    
    synchronized (this) {
        // If this is coming from the currently resumed activity, it is
        // effectively saying that app switches are allowed at this point.
        if (mMainStack.mResumedActivity != null
                && mMainStack.mResumedActivity.info.applicationInfo.uid ==
                        Binder.getCallingUid()) {
            mAppSwitchesAllowedTime = 0;
        }
    }
    int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
            resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
    return ret;
}
 
Example 49
Project: property-db   File: Activity.java View source code 6 votes vote down vote up
private void startIntentSenderForResultInner(IntentSender intent, int requestCode,
        Intent fillInIntent, int flagsMask, int flagsValues, Activity activity,
        Bundle options)
        throws IntentSender.SendIntentException {
    try {
        String resolvedType = null;
        if (fillInIntent != null) {
            fillInIntent.setAllowFds(false);
            resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver());
        }
        int result = ActivityManagerNative.getDefault()
            .startActivityIntentSender(mMainThread.getApplicationThread(), intent,
                    fillInIntent, resolvedType, mToken, activity.mEmbeddedID,
                    requestCode, flagsMask, flagsValues, options);
        if (result == ActivityManager.START_CANCELED) {
            throw new IntentSender.SendIntentException();
        }
        Instrumentation.checkStartActivityResult(result, null);
    } catch (RemoteException e) {
    }
    if (requestCode >= 0) {
        // If this start is requesting a result, we can avoid making
        // the activity visible until the result is received.  Setting
        // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
        // activity hidden during this time, to avoid flickering.
        // This can only be done when a result is requested because
        // that guarantees we will get information back when the
        // activity is finished, no matter what happens to it.
        mStartedActivity = true;
    }
}
 
Example 50
Project: googleio   File: BaseActivity.java View source code 6 votes vote down vote up
/**
 * Converts a fragment arguments bundle into an intent.
 */
public static Intent fragmentArgumentsToIntent(Bundle arguments) {
    Intent intent = new Intent();
    if (arguments == null) {
        return intent;
    }

    final Uri data = arguments.getParcelable("_uri");
    if (data != null) {
        intent.setData(data);
    }

    intent.putExtras(arguments);
    intent.removeExtra("_uri");
    return intent;
}
 
Example 51
Project: TextSecureSMP   File: MmsListener.java View source code 6 votes vote down vote up
private boolean isRelevant(Context context, Intent intent) {
  if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.DONUT) {
    return false;
  }

  if (!ApplicationMigrationService.isDatabaseImported(context)) {
    return false;
  }

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT &&
      Telephony.Sms.Intents.WAP_PUSH_RECEIVED_ACTION.equals(intent.getAction()) &&
      Util.isDefaultSmsProvider(context))
  {
    return false;
  }

  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT &&
      TextSecurePreferences.isInterceptAllMmsEnabled(context))
  {
    return true;
  }

  byte[] mmsData   = intent.getByteArrayExtra("data");
  PduParser parser = new PduParser(mmsData);
  GenericPdu pdu   = parser.parse();

  if (pdu == null || pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) {
    Log.w(TAG, "Received Invalid notification PDU");
    return false;
  }

  NotificationInd notificationPdu = (NotificationInd)pdu;

  if (notificationPdu.getSubject() == null)
    return false;

  return WirePrefix.isEncryptedMmsSubject(notificationPdu.getSubject().getString());
}
 
Example 52
Project: afwall   File: PackageBroadcast.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {

	Uri inputUri = Uri.parse(intent.getDataString());

	if (!inputUri.getScheme().equals("package")) {
		Log.d("AFWall+", "Intent scheme was not 'package'");
		return;
	}

	if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
		// Ignore application updates
		final boolean replacing = intent.getBooleanExtra(
				Intent.EXTRA_REPLACING, false);
		if (!replacing) {
			// Update the Firewall if necessary
			 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -123);
                Api.applicationRemoved(context, uid);
                Api.removeCacheLabel(intent.getData().getSchemeSpecificPart(),context);
                // Force app list reload next time
                Api.applications = null;
		}
	} else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {

		final boolean updateApp = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);

		if (updateApp) {
			// dont do anything
			//1 check the package already added in firewall

		} else {
			// Force app list reload next time
			Api.applications = null;
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			boolean isNotify = prefs.getBoolean("notifyAppInstall", false);
			if (isNotify && Api.isEnabled(context)) {
				String added_package = intent.getData().getSchemeSpecificPart();
				final PackageManager pkgmanager = context.getPackageManager();
				String label = null;
				try {
					label = pkgmanager.getApplicationLabel(pkgmanager.getApplicationInfo(added_package, 0)).toString();
				} catch (NameNotFoundException e) {
				}
				if (PackageManager.PERMISSION_GRANTED == pkgmanager.checkPermission(Manifest.permission.INTERNET,added_package)) {
					notifyApp(context, intent, label);
				}
			}
		}
	}
}
 
Example 53
Project: application-cafe-jeunesse-android   File: NavigationDrawerActivity.java View source code 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    // Handle action buttons
    switch (item.getItemId()) {
        case R.id.action_websearch:
            // create intent to perform web search for this planet
            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
            intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
            // catch event that there's no activity to handle intent
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
 
Example 54
Project: TextSecureSMP   File: ConversationActivity.java View source code 6 votes vote down vote up
private void handleDial(Recipient recipient) {
  try {
    if (recipient == null) return;

    Intent dialIntent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse("tel:" + recipient.getNumber()));
    startActivity(dialIntent);
  } catch (ActivityNotFoundException anfe) {
    Log.w(TAG, anfe);
    Dialogs.showAlertDialog(this,
                         getString(R.string.ConversationActivity_calls_not_supported),
                         getString(R.string.ConversationActivity_this_device_does_not_appear_to_support_dial_actions));
  }
}
 
Example 55
Project: packages_apps_Launcher2   File: LiveFolderAdapter.java View source code 6 votes vote down vote up
public void bindView(View view, Context context, Cursor cursor) {
    final ViewHolder holder = (ViewHolder) view.getTag();

    holder.id = cursor.getLong(holder.idIndex);
    final Drawable icon = loadIcon(context, cursor, holder);

    holder.name.setText(cursor.getString(holder.nameIndex));

    if (!mIsList) {
        holder.name.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null);
    } else {
        final boolean hasIcon = icon != null;
        holder.icon.setVisibility(hasIcon ? View.VISIBLE : View.GONE);
        if (hasIcon) holder.icon.setImageDrawable(icon);

        if (holder.descriptionIndex != -1) {
            final String description = cursor.getString(holder.descriptionIndex);
            if (description != null) {
                holder.description.setText(description);
                holder.description.setVisibility(View.VISIBLE);
            } else {
                holder.description.setVisibility(View.GONE);                    
            }
        } else {
            holder.description.setVisibility(View.GONE);                
        }
    }

    if (holder.intentIndex != -1) {
        try {
            holder.intent = Intent.parseUri(cursor.getString(holder.intentIndex), 0);
        } catch (URISyntaxException e) {
            // Ignore
        }
    } else {
        holder.useBaseIntent = true;
    }
}
 
Example 56
Project: packages_apps_Phone   File: PhoneUtils.java View source code 6 votes vote down vote up
/**
* This function is called when phone answers or places a call.
* Check if the phone is in a car dock or desk dock.
* If yes, turn on the speaker, when no wired or BT headsets are connected.
* Otherwise do nothing.
*/
private static void activateSpeakerIfDocked(Phone phone) {
    if (DBG) log("activateSpeakerIfDocked()...");

    if (PhoneApp.mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED) {
        if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker.");
        PhoneApp app = PhoneApp.getInstance();
        BluetoothHandsfree bthf = app.getBluetoothHandsfree();

        if (!app.isHeadsetPlugged() && !(bthf != null && bthf.isAudioOn())) {
            turnOnSpeaker(phone.getContext(), true, true);
        }
    }
}
 
Example 57
Project: AmazeFileManager   File: MediaStoreUtil.java View source code 6 votes vote down vote up
public static final void addFileToMediaStore(final String path,Context context) {
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File file = new File(path);
    Uri contentUri = Uri.fromFile(file);
    mediaScanIntent.setData(contentUri);
    context.sendBroadcast(mediaScanIntent);
}
 
Example 58
Project: mtdtool   File: ToggleAirplaneModeActivity.java View source code 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_toggle_airplane_mode);
    
    // Check the current value for airplane mode.
    boolean isEnabled = 
    		Settings.System.getInt(
    				getContentResolver(), 
    				Settings.System.AIRPLANE_MODE_ON, 0) == 1;
    
    // Toggle airplane mode.
    Settings.System.putInt(
    		getContentResolver(), 
    		Settings.System.AIRPLANE_MODE_ON, 
    		isEnabled ? 0:1);
    
    // Post an intent to reload
    Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    intent.putExtra("state", !isEnabled);
    sendBroadcast(intent);
}
 
Example 59
Project: packages_apps_Launcher2   File: WidgetCursorAdapter.java View source code 6 votes vote down vote up
/**
 * Collect arrays and put them together
 *
 * @param t
 * @param ids
 * @param c
 * @param u
 *            uri indices; could be zero, IMPOSSIBLE_INDEX will be used
 */
private void generateItemMapping(Intent intent) {

    // Read the mapping data
    int[] viewTypes = intent
            .getIntArrayExtra(LauncherIntent.Extra.Scroll.Mapping.EXTRA_VIEW_TYPES);
    int[] viewIds = intent.getIntArrayExtra(LauncherIntent.Extra.Scroll.Mapping.EXTRA_VIEW_IDS);
    int[] cursorIndices = intent
            .getIntArrayExtra(LauncherIntent.Extra.Scroll.Mapping.EXTRA_CURSOR_INDICES);
    int[] defaultResources = intent
            .getIntArrayExtra(LauncherIntent.Extra.Scroll.Mapping.EXTRA_DEFAULT_RESOURCES);
    boolean[] viewClickable = intent
            .getBooleanArrayExtra(LauncherIntent.Extra.Scroll.Mapping.EXTRA_VIEW_CLICKABLE);

    // Check
    if (viewTypes == null || viewIds == null || cursorIndices == null)
        throw (new IllegalArgumentException("A mapping component is missing"));

    if (viewTypes.length == viewIds.length && viewTypes.length == cursorIndices.length) {
    } else
        throw (new IllegalArgumentException("Mapping inconsistent"));

    // Init mapping array
    final int size = viewTypes.length;
    mItemMappings = new ItemMapping[size];
    for (int i = size - 1; i >= 0; i--)
        mItemMappings[i] = new ItemMapping(viewTypes[i], viewIds[i], cursorIndices[i]);

    // Put extra data in if they are available
    if (viewClickable != null && viewClickable.length == size)
        for (int i = size - 1; i >= 0; i--)
            mItemMappings[i].clickable = viewClickable[i];

    if (defaultResources != null && defaultResources.length == size)
        for (int i = size - 1; i >= 0; i--)
            mItemMappings[i].defaultResource = defaultResources[i];

}
 
Example 60
Project: sawan-bar   File: PhoneUtils.java View source code 6 votes vote down vote up
/**
* This function is called when phone answers or places a call.
* Check if the phone is in a car dock or desk dock.
* If yes, turn on the speaker, when no wired or BT headsets are connected.
* Otherwise do nothing.
*/
private static void activateSpeakerIfDocked(Phone phone) {
    if (DBG) log("activateSpeakerIfDocked()...");

    if (PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_DESK ||
            PhoneApp.mDockState == Intent.EXTRA_DOCK_STATE_CAR) {
        if (DBG) log("activateSpeakerIfDocked(): In a dock -> may need to turn on speaker.");
        PhoneApp app = PhoneApp.getInstance();
        BluetoothHandsfree bthf = app.getBluetoothHandsfree();

        if (!app.isHeadsetPlugged() && !(bthf != null && bthf.isAudioOn())) {
            turnOnSpeaker(phone.getContext(), true, true);
        }
    }
}
 
Example 61
Project: WiFi-Automatic   File: Preferences.java View source code 6 votes vote down vote up
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    // action bar overflow menu
    switch (item.getItemId()) {
        case R.id.enable:

            break;
        case R.id.action_wifi_adv:
            try {
                startActivity(new Intent(Settings.ACTION_WIFI_IP_SETTINGS)
                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            } catch (Exception e) {
                Toast.makeText(this, R.string.settings_not_found_, Toast.LENGTH_SHORT).show();
            }
            break;
        case R.id.action_apps:
            try {
                startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("market://search?q=pub:j4velin"))
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET));
            } catch (ActivityNotFoundException anf) {
                startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("https://play.google.com/store/apps/developer?id=j4velin"))
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET));
            }
            break;
        case R.id.action_donate:
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://j4velin-systems.de/donate.php"))
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
            break;
        default:
            return super.onOptionsItemSelected(item);
    }
    return true;
}
 
Example 62
Project: packages_apps_Launcher2   File: Launcher.java View source code 6 votes vote down vote up
/**
 * Launches the intent referred by the clicked shortcut.
 *
 * @param v The view representing the clicked shortcut.
 */
public void onClick(View v) {
    Object tag = v.getTag();
    if (tag instanceof ShortcutInfo) {
        // Open shortcut
        final Intent intent = ((ShortcutInfo) tag).intent;
        int[] pos = new int[2];
        v.getLocationOnScreen(pos);
        intent.setSourceBounds(new Rect(pos[0], pos[1],
                pos[0] + v.getWidth(), pos[1] + v.getHeight()));
        startActivitySafely(intent, tag);
    } else if (tag instanceof FolderInfo) {
        handleFolderClick((FolderInfo) tag);
    } else if (v == mHandleView) {
        if (isAllAppsVisible()) {
            closeAllApps(true);
        } else {
            showAllApps(true);
        }
    }
}
 
Example 63
Project: TrustedIntents   File: TrustedIntents.java View source code 6 votes vote down vote up
/**
 * Check an [email protected] Intent} is trusted based on the [email protected] packageName} set
 * by [email protected] Intent#setPackage(String)}
 *
 * @param intent the one to check
 * @return whether the [email protected] Intent}'s receiver is trusted
 */
public boolean isReceiverTrusted(Intent intent) {
    if (!isIntentSane(intent))
        return false;
    String packageName = intent.getPackage();
    if (TextUtils.isEmpty(packageName)) {
        packageName = intent.getComponent().getPackageName();
    }
    return isPackageNameTrusted(packageName);
}
 
Example 64
Project: angularjs-navigation-master-detail   File: CordovaUriHelper.java View source code 6 votes vote down vote up
/**
 * Give the host application a chance to take over the control when a new url
 * is about to be loaded in the current WebView.
 *
 * @param view          The WebView that is initiating the callback.
 * @param url           The url to be loaded.
 * @return              true to override, false for default behavior
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
boolean shouldOverrideUrlLoading(WebView view, String url) {
    // Give plugins the chance to handle the url
    if (this.appView.pluginManager.onOverrideUrlLoading(url)) {
        // Do nothing other than what the plugins wanted.
        // If any returned true, then the request was handled.
        return true;
    }
    else if(url.startsWith("file://") | url.startsWith("data:"))
    {
        //This directory on WebKit/Blink based webviews contains SQLite databases!
        //DON'T CHANGE THIS UNLESS YOU KNOW WHAT YOU'RE DOING!
        return url.contains("app_webview");
    }
    else if (appView.getWhitelist().isUrlWhiteListed(url)) {
        // Allow internal navigation
        return false;
    }
    else if (appView.getExternalWhitelist().isUrlWhiteListed(url))
    {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setComponent(null);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                intent.setSelector(null);
            }
            this.cordova.getActivity().startActivity(intent);
            return true;
        } catch (android.content.ActivityNotFoundException e) {
            LOG.e(TAG, "Error loading url " + url, e);
        }
    }
    // Intercept the request and do nothing with it -- block it
    return true;
}
 
Example 65
Project: WiFi-Automatic   File: ScreenChangeDetector.java View source code 6 votes vote down vote up
@Override
public void onReceive(final Context context, final Intent intent) {
    if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
        sendBroadcast(new Intent(context, Receiver.class).setAction(SCREEN_OFF_ACTION));
    } else if (Intent.ACTION_SCREEN_ON.equals(intent.getAction()) &&
            !((KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE))
                    .inKeyguardRestrictedInputMode()) {
        // SCREEN_ON is only send if there is no lockscreen active! Otherwise the Receiver will get USER_PRESENT
        sendBroadcast(new Intent(context, Receiver.class).setAction(SCREEN_ON_ACTION));
    }
}
 
Example 66
Project: DemoProject   File: SampleMediaRouteProvider.java View source code 6 votes vote down vote up
@Override
public boolean onControlRequest(Intent intent, ControlRequestCallback callback) {
    Log.d(TAG, mRouteId + ": Received control request " + intent);
    String action = intent.getAction();
    if (intent.hasCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)) {
        boolean success = false;
        if (action.equals(MediaControlIntent.ACTION_PLAY)) {
            success = handlePlay(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_ENQUEUE)) {
            success = handleEnqueue(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_REMOVE)) {
            success = handleRemove(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_SEEK)) {
            success = handleSeek(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_GET_STATUS)) {
            success = handleGetStatus(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_PAUSE)) {
            success = handlePause(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_RESUME)) {
            success = handleResume(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_STOP)) {
            success = handleStop(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_START_SESSION)) {
            success = handleStartSession(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_GET_SESSION_STATUS)) {
            success = handleGetSessionStatus(intent, callback);
        } else if (action.equals(MediaControlIntent.ACTION_END_SESSION)) {
            success = handleEndSession(intent, callback);
        }
        Log.d(TAG, mSessionManager.toString());
        return success;
    }

    if (action.equals(ACTION_GET_TRACK_INFO)
            && intent.hasCategory(CATEGORY_SAMPLE_ROUTE)) {
        Bundle data = new Bundle();
        PlaylistItem item = mSessionManager.getCurrentItem();
        if (item != null) {
            data.putString(TRACK_INFO_DESC, item.toString());
            data.putParcelable(TRACK_INFO_SNAPSHOT, mPlayer.getSnapshot());
        }
        if (callback != null) {
            callback.onResult(data);
        }
        return true;
    }
    return false;
}
 
Example 67
Project: TextSecureSMP   File: GroupMembersDialog.java View source code 6 votes vote down vote up
@Override
public void onClick(DialogInterface dialogInterface, int item) {
  Recipient recipient = groupMembers.get(item);

  if (recipient.getContactUri() != null) {
    ContactsContract.QuickContact.showQuickContact(context, new Rect(0,0,0,0),
                                                   recipient.getContactUri(),
                                                   ContactsContract.QuickContact.MODE_LARGE, null);
  } else {
    final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
    intent.putExtra(ContactsContract.Intents.Insert.PHONE, recipient.getNumber());
    intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
    context.startActivity(intent);
  }
}
 
Example 68
Project: weather-notification-android   File: WeatherNotificationManagerTest.java View source code 6 votes vote down vote up
public void testCreateIntent2() throws Exception {
    Weather weather = WeatherUtils.createWeather(getInstrumentation().getContext());
    Intent intent = WeatherNotificationManager.createIntent2(true, weather);
    Parcel parcel = Parcel.obtain();
    parcel.writeParcelable(intent, 0);
    parcel.setDataPosition(0);
    intent = (Intent)parcel.readParcelable(getInstrumentation().getTargetContext().getClassLoader());
    intent.setExtrasClassLoader(getInstrumentation().getTargetContext().getClassLoader());
    System.out.println(intent);
    System.out.println("extras: " + intent.getExtras().keySet());
    System.out.println("enabled: " + intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false));
    System.out.println("extra weather: " + intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER));
    assertEquals(IntentParameters.ACTION_WEATHER_UPDATE_2, intent.getAction());
    assertTrue(intent.hasExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION));
    assertTrue(intent.getBooleanExtra(IntentParameters.EXTRA_ENABLE_NOTIFICATION, false));
    assertTrue(intent.hasExtra(IntentParameters.EXTRA_WEATHER));
    WeatherUtils.checkWeather((Weather)intent.getParcelableExtra(IntentParameters.EXTRA_WEATHER),
            WeatherUtils.Version.V_0_3);
}
 
Example 69
Project: TextSecureSMP   File: MarkReadReceiver.java View source code 6 votes vote down vote up
@Override
public void onReceive(final Context context, Intent intent) {
  if (!intent.getAction().equals(CLEAR_ACTION))
    return;

  final long[]       threadIds    = intent.getLongArrayExtra("thread_ids");
  final MasterSecret masterSecret = intent.getParcelableExtra("master_secret");

  if (threadIds != null && masterSecret != null) {
    Log.w("MarkReadReceiver", "threadIds length: " + threadIds.length);

    ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE))
        .cancel(MessageNotifier.NOTIFICATION_ID);

    new AsyncTask<Void, Void, Void>() {
      @Override
      protected Void doInBackground(Void... params) {
        for (long threadId : threadIds) {
          Log.w("MarkReadReceiver", "Marking as read: " + threadId);
          DatabaseFactory.getThreadDatabase(context).setRead(threadId);
        }

        MessageNotifier.updateNotification(context, masterSecret);
        return null;
      }
    }.execute();
  }
}
 
Example 70
Project: AmazeFileManager   File: MainActivity.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent != null) {
        if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED)) {
            Toast.makeText(con, "Media Mounted", Toast.LENGTH_SHORT).show();
            String a = intent.getData().getPath();
            if (a != null && a.trim().length() != 0 && new File(a).exists() && new File(a).canExecute()) {
                list.add(new EntryItem(new File(a).getName(), a, ContextCompat
                        .getDrawable(mainActivity, R.drawable.ic_sd_storage_white_56dp)));
                adapter = new DrawerAdapter(con, list, MainActivity.this, Sp);
                mDrawerList.setAdapter(adapter);
            } else {
                refreshDrawer();
            }
        } else if (intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED)) {

            refreshDrawer();
        }
    }
}
 
Example 71
Project: packages_apps_Launcher2   File: ApplicationInfo.java View source code 6 votes vote down vote up
public ApplicationInfo(ApplicationInfo info) {
    super(info);
    componentName = info.componentName;
    title = info.title.toString();
    intent = new Intent(info.intent);
    if (info.iconResource != null) {
        iconResource = new Intent.ShortcutIconResource();
        iconResource.packageName = info.iconResource.packageName;
        iconResource.resourceName = info.iconResource.resourceName;
    }
    icon = info.icon;
    filtered = info.filtered;
    customIcon = info.customIcon;
}
 
Example 72
Project: googleio   File: HomeActivity.java View source code 6 votes vote down vote up
private void triggerRefresh() {
    final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, SyncService.class);
    intent.putExtra(SyncService.EXTRA_STATUS_RECEIVER, mSyncStatusUpdaterFragment.mReceiver);
    startService(intent);

    if (mTagStreamFragment != null) {
        mTagStreamFragment.refresh();
    }
}
 
Example 73
Project: spikes   File: TwitterOnPrepareSharingIntentListener.java View source code 6 votes vote down vote up
@Override
public Intent onPrepareSharingIntent(Intent intent) {
    if (isIntentTargetATwitterClient(intent)) {
        CharSequence originalSubject = intent.getCharSequenceExtra(Intent.EXTRA_SUBJECT);
        String subject = originalSubject != null ? originalSubject.toString() : null;

        MessageComposer composer = createComposer();
        intent.putExtras(composer.composeToBundle(subject, url));
    }

    return intent;
}
 
Example 74
Project: packages_apps_Launcher2   File: Launcher.java View source code 6 votes vote down vote up
private void pickHotSeatShortcut(int hotseatNumber) {
	mHotseatNumber = hotseatNumber;
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    Intent pickIntent = new Intent(Intent.ACTION_PICK_ACTIVITY);
    pickIntent.putExtra(Intent.EXTRA_INTENT, mainIntent);
    startActivityForResult(pickIntent, REQUEST_HOTSEAT_APPLICATION);
}
 
Example 75
Project: DemoProject   File: IntentActivityFlags.java View source code 6 votes vote down vote up
/**
 * This creates an array of Intent objects representing the back stack
 * for a user going into the Views/Lists API demos.
 */

private Intent[] buildIntentsToViewsLists() {
    // We are going to rebuild our task with a new back stack.  This will
    // be done by launching an array of Intents, representing the new
    // back stack to be created, with the first entry holding the root
    // and requesting to reset the back stack.
    Intent[] intents = new Intent[3];

    // First: root activity of ApiDemos.
    // This is a convenient way to make the proper Intent to launch and
    // reset an application's task.
    intents[0] = Intent.makeRestartActivityTask(new ComponentName(this,
            com.example.android.apis.ApiDemos.class));

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setClass(IntentActivityFlags.this, com.example.android.apis.ApiDemos.class);
    intent.putExtra("com.example.android.apis.Path", "Views");
    intents[1] = intent;

    intent = new Intent(Intent.ACTION_MAIN);
    intent.setClass(IntentActivityFlags.this, com.example.android.apis.ApiDemos.class);
    intent.putExtra("com.example.android.apis.Path", "Views/Lists");

    intents[2] = intent;
    return intents;
}
 
Example 76
Project: BioWiki   File: MediaBrowserActivity.java View source code 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (BioWiki.wpDB == null) {
        Toast.makeText(this, R.string.fatal_db_error, Toast.LENGTH_LONG).show();
        finish();
        return;
    }

    setTitle(R.string.media);

    createMenuDrawer(R.layout.media_browser_activity);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowTitleEnabled(true);

    FragmentManager fm = getSupportFragmentManager();
    fm.addOnBackStackChangedListener(mOnBackStackChangedListener);
    FragmentTransaction ft = fm.beginTransaction();
    setupBaseLayout();

    mMediaAddFragment = (MediaAddFragment) fm.findFragmentById(R.id.mediaAddFragment);
    mMediaGridFragment = (MediaGridFragment) fm.findFragmentById(R.id.mediaGridFragment);

    mMediaItemFragment = (MediaItemFragment) fm.findFragmentByTag(MediaItemFragment.TAG);
    if (mMediaItemFragment != null)
        ft.hide(mMediaGridFragment);

    mMediaEditFragment = (MediaEditFragment) fm.findFragmentByTag(MediaEditFragment.TAG);
    if (mMediaEditFragment != null && !mMediaEditFragment.isInLayout())
        ft.hide(mMediaItemFragment);

    ft.commit();

    setupAddMenuPopup();

    String action = getIntent().getAction();
    if (Intent.ACTION_SEND.equals(action) || Intent.ACTION_SEND_MULTIPLE.equals(action)) {
        // We arrived here from a share action
        uploadSharedFiles();
    }
}
 
Example 77
Project: packages_apps_BlackICEControl   File: ShortcutPickerHelper.java View source code 6 votes vote down vote up
private String getFriendlyActivityName(Intent intent, boolean labelOnly) {
    PackageManager pm = mParent.getActivity().getPackageManager();
    ActivityInfo ai = intent.resolveActivityInfo(pm, PackageManager.GET_ACTIVITIES);
    String friendlyName = null;

    if (ai != null) {
        friendlyName = ai.loadLabel(pm).toString();
        if (friendlyName == null && !labelOnly) {
            friendlyName = ai.name;
        }
    }

    return friendlyName != null || labelOnly ? friendlyName : intent.toUri(0);
}
 
Example 78
Project: android-codelab-watchface   File: MyWatchFaceService.java View source code 6 votes vote down vote up
private void registerReceiver() {
    if (mRegisteredTimeZoneReceiver) {
        return;
    }
    mRegisteredTimeZoneReceiver = true;
    IntentFilter filter = new IntentFilter(Intent.ACTION_TIMEZONE_CHANGED);
    MyWatchFaceService.this.registerReceiver(mTimeZoneReceiver, filter);
}
 
Example 79
Project: Terminal   File: Term.java View source code 6 votes vote down vote up
private void populateViewFlipper() {
	if (mTermService != null) {
		mTermSessions = mTermService.getSessions();
		mTermSessions.addCallback(this);

		if (mTermSessions.size() == 0) {
			try {
                   mTermSessions.add(createTermSession());
               } catch (IOException e) {
                   Toast.makeText(this, "Failed to start terminal session", Toast.LENGTH_LONG).show();
                   finish();
                   return;
               }
		}

		for (TermSession session : mTermSessions) {
			EmulatorView view = createEmulatorView(session);
			mViewFlipper.addView(view);
		}

		updatePrefs();

		Intent intent = getIntent();
		int flags = intent.getFlags();
		String action = intent.getAction();
		if ((flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0
				&& action != null) {
			if (action.equals(RemoteInterface.PRIVACT_OPEN_NEW_WINDOW)) {
				mViewFlipper.setDisplayedChild(mTermSessions.size() - 1);
			} else if (action.equals(RemoteInterface.PRIVACT_SWITCH_WINDOW)) {
				int target = intent.getIntExtra(
						RemoteInterface.PRIVEXTRA_TARGET_WINDOW, -1);
				if (target >= 0) {
					mViewFlipper.setDisplayedChild(target);
				}
			}
		}

		mViewFlipper.resumeCurrentView();
	}
}
 
Example 80
Project: property-db   File: LocalGrantedReceiver.java View source code 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    try {
        IBinder caller = intent.getIBinderExtra("caller");
        Parcel data = Parcel.obtain();
        data.writeInterfaceToken(LaunchpadActivity.LAUNCH);
        data.writeString(BroadcastTest.RECEIVER_LOCAL);
        caller.transact(BroadcastTest.GOT_RECEIVE_TRANSACTION, data, null, 0);
        data.recycle();
    } catch (RemoteException ex) {
    }
}
 
Example 81
Project: packages_apps_Launcher2   File: Launcher.java View source code 6 votes vote down vote up
private void startWallpaper() {
        closeAllApps(true);
        final Intent pickWallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);
        Intent chooser = Intent.createChooser(pickWallpaper,
                getText(R.string.chooser_wallpaper));
        // NOTE: Adds a configure option to the chooser if the wallpaper supports it
        //       Removed in Eclair MR1
//        WallpaperManager wm = (WallpaperManager)
//                getSystemService(Context.WALLPAPER_SERVICE);
//        WallpaperInfo wi = wm.getWallpaperInfo();
//        if (wi != null && wi.getSettingsActivity() != null) {
//            LabeledIntent li = new LabeledIntent(getPackageName(),
//                    R.string.configure_wallpaper, 0);
//            li.setClassName(wi.getPackageName(), wi.getSettingsActivity());
//            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { li });
//        }
        startActivityForResult(chooser, REQUEST_PICK_WALLPAPER);
    }
 
Example 82
Project: dubsar_android   File: DubsarActivity.java View source code 6 votes vote down vote up
/**
 * To determine whether we're restarting the activity at the top of
 * the forward stack, we cannot just compare Intent references. We 
 * must examine the contents. Most intents have a URI in getData().
 * Some search queries have a null URI but a string extra 
 * SearchManager.QUERY. We also consider intent actions and components.
 * @param i1 one Intent
 * @param i2 another Intent
 * @return whether the two Intents represent the same activity
 */
public static boolean equalIntents(Intent i1, Intent i2) {
	if (i1 == null || i2 == null) {
		return i1 == i2;
	}
	
	String query1 = i1.getStringExtra(SearchManager.QUERY);
	String query2 = i2.getStringExtra(SearchManager.QUERY);

	boolean filterEquals = i1.filterEquals(i2);
	
	/*
	 * Intent.filterEquals() does not take extras into account, so we do.
	 */
	return filterEquals &&
			((query1 == null && query2 == null) ||
			(query1 != null && query2 != null && query1.equals(query2)));
}
 
Example 83
Project: BambooPlayer   File: VideoActivity.java View source code 6 votes vote down vote up
private void parseIntent(Intent i) {

		Uri dat = getIntentUri(i);
		if (dat == null)
			resultFinish(RESULT_FAILED);

		String datString = dat.toString();
		if (!datString.equals(dat.toString()))
			dat = Uri.parse(datString);

		mUri = dat;

		mNeedLock = i.getBooleanExtra("lockScreen", false);
		mDisplayName = i.getStringExtra("displayName");
		mFromStart = i.getBooleanExtra("fromStart", false);
		mSaveUri = i.getBooleanExtra("saveUri", true);
		mStartPos = i.getFloatExtra("startPosition", -1.0f);
		mLoopCount = i.getIntExtra("loopCount", 1);
		mParentId = i.getIntExtra("parentId", 0);
		mSubPath = i.getStringExtra("subPath");
		mSubShown = i.getBooleanExtra("subShown", true);
		mIsHWCodec = i.getBooleanExtra("hwCodec", false);
	}
 
Example 84
Project: sawan-bar   File: SimContacts.java View source code 6 votes vote down vote up
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_CALL: {
            if (mCursor != null && mCursor.moveToPosition(getSelectedItemPosition())) {
                String phoneNumber = mCursor.getString(NUMBER_COLUMN);
                if (phoneNumber == null || !TextUtils.isGraphic(phoneNumber)) {
                    // There is no number entered.
                    //TODO play error sound or something...
                    return true;
                }
                Intent intent = new Intent(Intent.ACTION_CALL_PRIVILEGED,
                        Uri.fromParts("tel", phoneNumber, null));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                      | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                finish();
                return true;
            }
        }
    }
    return super.onKeyDown(keyCode, event);
}
 
Example 85
Project: DemoProject   File: LauncherShortcuts.java View source code 6 votes vote down vote up
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    // Resolve the intent

    final Intent intent = getIntent();
    final String action = intent.getAction();

    // If the intent is a request to create a shortcut, we'll do that and exit

    if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) {
        setupShortcut();
        finish();
        return;
    }

    // If we weren't launched with a CREATE_SHORTCUT intent, simply put up an informative
    // display.

    // Inflate our UI from its XML layout description.

    setContentView(R.layout.launcher_shortcuts);

    // Provide a lightweight view of the Intent that launched us

    TextView intentInfo = (TextView) findViewById(R.id.txt_shortcut_intent);
    String info = intent.toString();
    String extra = intent.getStringExtra(EXTRA_KEY);
    if (extra != null) {
        info = info + " " + extra;
    }
    intentInfo.setText(info);
}
 
Example 86
Project: campus   File: UIHelper.java View source code 6 votes vote down vote up
/**
 * ????
 * 
 * @param activity
 */
public static void showProvince(Activity activity,
		ArrayList<Integer> selectProvinceList) {
	Intent intent = new Intent(activity, ProvinceActivity.class);
	intent.putIntegerArrayListExtra("selectedList", selectProvinceList);
	activity.startActivityForResult(intent, REQUEST_PROVINCE_FOR_RESULT);
}
 
Example 87
Project: packages_apps_BlackICEControl   File: ShortcutPickerHelper.java View source code 6 votes vote down vote up
private void completeSetCustomShortcut(Intent data) {
    Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT);
    /* preserve shortcut name, we want to restore it later */
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME));
    String appUri = intent.toUri(0);
    appUri = appUri.replaceAll("com.android.contacts.action.QUICK_CONTACT",
            "android.intent.action.VIEW");
    /* Try to get the icon (if any) */
    Bitmap bmp = null;
    Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
    if (extra != null && extra instanceof Bitmap)
        bmp = (Bitmap) extra;
    if (bmp == null) {
        extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
        if (extra != null && extra instanceof Intent.ShortcutIconResource) {
            try {
                Intent.ShortcutIconResource iconResource = (ShortcutIconResource) extra;
                final PackageManager packageManager = mParent.getActivity().getPackageManager();
                Resources resources = packageManager.getResourcesForApplication(iconResource.packageName);
                final int id = resources.getIdentifier(iconResource.resourceName, null, null);
                bmp = BitmapFactory.decodeResource(resources, id);
            } catch (Exception e) {
                Log.w("ROMControl.ShortcutPicker", "Could not load shortcut icon: " + extra);
            }
        }
    }
    mListener.shortcutPicked(appUri, getFriendlyShortcutName(intent), bmp, false);
}
 
Example 88
Project: property-db   File: PhoneWindowManager.java View source code 6 votes vote down vote up
boolean needSensorRunningLp() {
    if (mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR
            || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR
            || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
            || mCurrentAppOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) {
        // If the application has explicitly requested to follow the
        // orientation, then we need to turn the sensor or.
        return true;
    }
    if ((mCarDockEnablesAccelerometer && mDockMode == Intent.EXTRA_DOCK_STATE_CAR) ||
            (mDeskDockEnablesAccelerometer && (mDockMode == Intent.EXTRA_DOCK_STATE_DESK
                    || mDockMode == Intent.EXTRA_DOCK_STATE_LE_DESK
                    || mDockMode == Intent.EXTRA_DOCK_STATE_HE_DESK))) {
        // enable accelerometer if we are docked in a dock that enables accelerometer
        // orientation management,
        return true;
    }
    if (mUserRotationMode == USER_ROTATION_LOCKED) {
        // If the setting for using the sensor by default is enabled, then
        // we will always leave it on.  Note that the user could go to
        // a window that forces an orientation that does not use the
        // sensor and in theory we could turn it off... however, when next
        // turning it on we won't have a good value for the current
        // orientation for a little bit, which can cause orientation
        // changes to lag, so we'd like to keep it always on.  (It will
        // still be turned off when the screen is off.)
        return false;
    }
    return true;
}
 
Example 89
Project: HoloDash   File: Utils.java View source code 6 votes vote down vote up
public static Intent getDefaultAlarmsIntent(Context context) {
    // TODO: consider using AlarmClock.ACTION_SET_ALARM, although it requires a permission
    PackageManager pm = context.getPackageManager();
    for (String packageName : CLOCK_PACKAGES) {
        try {
            ComponentName cn = new ComponentName(packageName,
                    "com.android.deskclock.AlarmClock");
            pm.getActivityInfo(cn, 0);
            return Intent.makeMainActivity(cn);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    }
    return getDefaultClockIntent(context);
}
 
Example 90
Project: AirPlayer   File: PlayMusicService.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    switch (intent.getAction()) {
        case NOTIFICATION_OPERATION:
            onNotificationActionsReceive(intent);
            break;
        case Intent.ACTION_HEADSET_PLUG:
            onHeadsetPlugActionReceive(intent);
            break;
    }
}
 
Example 91
Project: packages_apps_Launcher2   File: Launcher.java View source code 6 votes vote down vote up
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    // Close the menu
    if (Intent.ACTION_MAIN.equals(intent.getAction())) {
        // also will cancel mWaitingForResult.
        closeSystemDialogs();

        boolean alreadyOnHome = ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT)
                    != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        boolean allAppsVisible = isAllAppsVisible();
        if (!mWorkspace.isDefaultScreenShowing()) {
            mWorkspace.moveToDefaultScreen(alreadyOnHome && !allAppsVisible);
        }
        closeAllApps(alreadyOnHome && allAppsVisible);

        final View v = getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager)getSystemService(
                    INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
 
Example 92
Project: TestingStaff   File: GetFeedsService.java View source code 6 votes vote down vote up
@Override
public void onStart(Intent intent, int startId) {
	super.onStart(intent, startId);
	try {
		feedsToUpdate = intent.getIntegerArrayListExtra(Constants.FEEDS_TO_UPDATE);
		if (feedsToUpdate == null) feedsToUpdate = new ArrayList<Integer>();
	} catch (NullPointerException e) {
		feedsToUpdate = new ArrayList<Integer>();
	}
	
	startService();
}
 
Example 93
Project: FasterGallery   File: ImageGallery.java View source code 6 votes vote down vote up
private void setupInclusion() {
    mInclusion = ImageManager.INCLUDE_IMAGES | ImageManager.INCLUDE_VIDEOS;

    Intent intent = getIntent();
    if (intent != null) {
        String type = intent.resolveType(this);
        TextView leftText = (TextView) findViewById(R.id.left_text);
        if (type != null) {
            if (isImageType(type)) {
                mInclusion = ImageManager.INCLUDE_IMAGES;
                if (isPickIntent()) {
                    leftText.setText(R.string.pick_photos_gallery_title);
                } else {
                    leftText.setText(R.string.photos_gallery_title);
                }
            }
            if (isVideoType(type)) {
                mInclusion = ImageManager.INCLUDE_VIDEOS;
                if (isPickIntent()) {
                    leftText.setText(R.string.pick_videos_gallery_title);
                } else {
                    leftText.setText(R.string.videos_gallery_title);
                }
            }
        }
        Bundle extras = intent.getExtras();
        String title = (extras != null)
                ? extras.getString("windowTitle")
                : null;
        if (title != null && title.length() > 0) {
            leftText.setText(title);
        }

        if (extras != null) {
            mInclusion = (ImageManager.INCLUDE_IMAGES
                    | ImageManager.INCLUDE_VIDEOS)
                    & extras.getInt("mediaTypes", mInclusion);
        }

        if (extras != null && extras.getBoolean("pick-drm")) {
            Log.d(TAG, "pick-drm is true");
            mInclusion = ImageManager.INCLUDE_DRM_IMAGES;
        }
    }
}
 
Example 94
Project: sjtubbs   File: NewPostActivity.java View source code 6 votes vote down vote up
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
        super.onActivityResult(requestCode, resultCode, data);
        return;
    }

    switch (requestCode) {
        case REQUEST_CODE_CAMERA:
            System.out.println(photoPath);
            break;

        case REQUEST_CODE_GALLERY:
            if (data == null) {
                return;
            }
            if (data.getData() != null) {
                photoUris = new Uri[1];
                photoUris[0] = data.getData();
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    ClipData clipData = data.getClipData();
                    if (clipData != null) {
                        Uri[] uris = new Uri[clipData.getItemCount()];
                        for (int i = 0; i < clipData.getItemCount(); i++) {
                            uris[i] = clipData.getItemAt(i).getUri();
                        }
                        photoUris = uris;
                    }
                }
            }
            new UploadTask().execute(photoUris);
            break;

        default:
            super.onActivityResult(requestCode, resultCode, data);
    }
}
 
Example 95
Project: MobileSensing   File: BluetoothDeviceScanner.java View source code 6 votes vote down vote up
@Override
public void doHandleScanResults( Intent intent )
{
  String action = intent.getAction();
  
  if ( BluetoothDevice.ACTION_FOUND.equals( action ) )
  {
    TimeInformation ti = TimeProvider.getInstance().getAccurateTimeInformation();
    int samplePriority =
          getDevice().getConfiguration().getSamplePriority().ordinal();
    BluetoothDevice bluetoothDevice =
          intent.getParcelableExtra( BluetoothDevice.EXTRA_DEVICE );
    Short rssi = null;
    if ( intent.hasExtra( BluetoothDevice.EXTRA_RSSI ) )
    {
      rssi =
            intent.getShortExtra( BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE );
    }
    SampleFactory sampleFactory = SampleFactory.getInstance();
    Sample sample =
      sampleFactory.createSample( ti, getDevice().getDeviceIdentifier(),
              samplePriority, sampleFactory.createBluetoothSampleData(
                  bluetoothDevice, rssi ) );
    if ( sample != null )
      notify( sample );
  }
  else
  {
    if ( BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals( action ) )
    {
      // signal scan started to worker thread
      setLastScanFinished( false );
    }
    else if ( BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals( action ) )
    {
      // signal scan finished to worker thread
      setLastScanFinished( true );
    }
  }
}
 
Example 96
Project: notes   File: OFileManager.java View source code 6 votes vote down vote up
public void requestForFile(RequestType type) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_GET_CONTENT);
    switch (type) {
        case AUDIO:
            intent.setType("audio/*");
            requestIntent(intent, REQUEST_AUDIO);
            break;
        case IMAGE:
            if (Build.VERSION.SDK_INT < 19) {
                intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
            } else {
                intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
            }
            intent.setType("image/*");
            requestIntent(intent, REQUEST_IMAGE);
            break;
        case CAPTURE_IMAGE:
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, "Odoo Mobile Attachment");
            values.put(MediaStore.Images.Media.DESCRIPTION,
                    "Captured from Odoo Mobile App");
            newImageUri = mContext.getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, newImageUri);
            requestIntent(intent, REQUEST_CAMERA);
            break;
        case IMAGE_OR_CAPTURE_IMAGE:
            requestDialog(type);
            break;
        case FILE:
            intent.setType("application/*");
            requestIntent(intent, REQUEST_FILE);
            break;
        case ALL_FILE_TYPE:
            intent.setType("*/*");
            requestIntent(intent, REQUEST_ALL_FILE);
            break;
    }
}
 
Example 97
Project: property-db   File: DevicePolicyManagerService.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    final String action = intent.getAction();
    final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
            getSendingUserId());
    if (Intent.ACTION_BOOT_COMPLETED.equals(action)
            || ACTION_EXPIRED_PASSWORD_NOTIFICATION.equals(action)) {
        Slog.v(TAG, "Sending password expiration notifications for action " + action
                + " for user " + userHandle);
        mHandler.post(new Runnable() {
            public void run() {
                handlePasswordExpirationNotification(getUserData(userHandle));
            }
        });
    } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
        removeUserData(userHandle);
    } else if (Intent.ACTION_USER_STARTED.equals(action)
            || Intent.ACTION_PACKAGE_CHANGED.equals(action)
            || Intent.ACTION_PACKAGE_REMOVED.equals(action)
            || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {

        if (Intent.ACTION_USER_STARTED.equals(action)) {
            // Reset the policy data
            synchronized (DevicePolicyManagerService.this) {
                mUserData.remove(userHandle);
            }
        }

        handlePackagesChanged(userHandle);
    }
}
 
Example 98
Project: DemoProject   File: InstallApk.java View source code 6 votes vote down vote up
public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
    intent.setData(Uri.fromFile(prepareApk("HelloActivity.apk")));
    intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
    intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
    intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME,
            getApplicationInfo().packageName);
    startActivityForResult(intent, REQUEST_INSTALL);
}
 
Example 99
Project: property-db   File: ActivityManagerService.java View source code 6 votes vote down vote up
Intent createAppErrorIntentLocked(ProcessRecord r,
        long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
    ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
    if (report == null) {
        return null;
    }
    Intent result = new Intent(Intent.ACTION_APP_ERROR);
    result.setComponent(r.errorReportReceiver);
    result.putExtra(Intent.EXTRA_BUG_REPORT, report);
    result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    return result;
}
 
Example 100
Project: property-db   File: ServiceTestCase.java View source code 6 votes vote down vote up
/**
 * <p>
 *      Starts the service under test, in the same way as if it were started by
 *      [email protected] android.content.Context#bindService(Intent, ServiceConnection, int)
 *      Context.bindService(Intent, ServiceConnection, flags)} with an
 *      [email protected] android.content.Intent} that identifies a service.
 * </p>
 * <p>
 *      Notice that the parameters are different. You do not provide a
 *      [email protected] android.content.ServiceConnection} object or the flags parameter. Instead,
 *      you only provide the Intent. The method returns an object whose type is a
 *      subclass of [email protected] android.os.IBinder}, or null if the method fails. An IBinder
 *      object refers to a communication channel between the application and
 *      the service. The flag is assumed to be [email protected] android.content.Context#BIND_AUTO_CREATE}.
 * </p>
 * <p>
 *      See <a href="[email protected]}guide/components/aidl.html">Designing a Remote Interface
 *      Using AIDL</a> for more information about the communication channel object returned
 *      by this method.
 * </p>
 * Note:  To be able to use bindService in a test, the service must implement getService()
 * method. An example of this is in the ApiDemos sample application, in the
 * LocalService demo.
 *
 * @param intent An Intent object of the form expected by
 * [email protected] android.content.Context#bindService}.
 *
 * @return An object whose type is a subclass of IBinder, for making further calls into
 * the service.
 */
protected IBinder bindService(Intent intent) {
    if (!mServiceAttached) {
        setupService();
    }
    assertNotNull(mService);

    if (!mServiceCreated) {
        mService.onCreate();
        mServiceCreated = true;
    }
    // no extras are expected by unbind
    mServiceIntent = intent.cloneFilter();
    IBinder result = mService.onBind(intent);

    mServiceBound = true;
    return result;
}
 
Example 101
Project: property-db   File: TaskRecord.java View source code 6 votes vote down vote up
void setIntent(Intent _intent, ActivityInfo info) {
    stringName = null;

    if (info.targetActivity == null) {
        if (_intent != null) {
            // If this Intent has a selector, we want to clear it for the
            // recent task since it is not relevant if the user later wants
            // to re-launch the app.
            if (_intent.getSelector() != null || _intent.getSourceBounds() != null) {
                _intent = new Intent(_intent);
                _intent.setSelector(null);
                _intent.setSourceBounds(null);
            }
        }
        if (ActivityManagerService.DEBUG_TASKS) Slog.v(ActivityManagerService.TAG,
                "Setting Intent of " + this + " to " + _intent);
        intent = _intent;
        realActivity = _intent != null ? _intent.getComponent() : null;
        origActivity = null;
    } else {
        ComponentName targetComponent = new ComponentName(
                info.packageName, info.targetActivity);
        if (_intent != null) {
            Intent targetIntent = new Intent(_intent);
            targetIntent.setComponent(targetComponent);
            targetIntent.setSelector(null);
            targetIntent.setSourceBounds(null);
            if (ActivityManagerService.DEBUG_TASKS) Slog.v(ActivityManagerService.TAG,
                    "Setting Intent of " + this + " to target " + targetIntent);
            intent = targetIntent;
            realActivity = targetComponent;
            origActivity = _intent.getComponent();
        } else {
            intent = null;
            realActivity = targetComponent;
            origActivity = new ComponentName(info.packageName, info.name);
        }
    }

    if (intent != null &&
            (intent.getFlags()&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
        // Once we are set to an Intent with this flag, we count this
        // task as having a true root activity.
        rootWasReset = true;
    }

    if (info.applicationInfo != null) {
        userId = UserHandle.getUserId(info.applicationInfo.uid);
    }
}
 
Example 102
Project: property-db   File: ActivityManagerService.java View source code 6 votes vote down vote up
final Intent verifyBroadcastLocked(Intent intent) {
    // Refuse possible leaked file descriptors
    if (intent != null && intent.hasFileDescriptors() == true) {
        throw new IllegalArgumentException("File descriptors passed in Intent");
    }

    int flags = intent.getFlags();

    if (!mProcessesReady) {
        // if the caller really truly claims to know what they're doing, go
        // ahead and allow the broadcast without launching any receivers
        if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
            intent = new Intent(intent);
            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
        } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
            Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
                    + " before boot completion");
            throw new IllegalStateException("Cannot broadcast before boot completed");
        }
    }

    if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
        throw new IllegalArgumentException(
                "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
    }

    return intent;
}
 
Example 103
Project: property-db   File: PhoneStatusBar.java View source code 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    if (DEBUG) Slog.v(TAG, "onReceive: " + intent);
    String action = intent.getAction();
    if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
        int flags = CommandQueue.FLAG_EXCLUDE_NONE;
        if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
            String reason = intent.getStringExtra("reason");
            if (reason != null && reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                flags |= CommandQueue.FLAG_EXCLUDE_RECENTS_PANEL;
            }
        }
        animateCollapsePanels(flags);
    }
    else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
        // no waiting!
        makeExpandedInvisible();
        notifyNavigationBarScreenOn(false);
    }
    else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) {
        if (DEBUG) {
            Slog.v(TAG, "configuration changed: " + mContext.getResources().getConfiguration());
        }
        mDisplay.getSize(mCurrentDisplaySize);

        updateResources();
        repositionNavigationBar();
        updateExpandedViewPos(EXPANDED_LEAVE_ALONE);
        updateShowSearchHoldoff();
    }
    else if (Intent.ACTION_SCREEN_ON.equals(action)) {
        // work around problem where mDisplay.getRotation() is not stable while screen is off (bug 7086018)
        repositionNavigationBar();
        notifyNavigationBarScreenOn(true);
    }
}
 
Example 104
Project: property-db   File: WallpaperManagerService.java View source code 6 votes vote down vote up
private void notifyCallbacksLocked(WallpaperData wallpaper) {
    final int n = wallpaper.callbacks.beginBroadcast();
    for (int i = 0; i < n; i++) {
        try {
            wallpaper.callbacks.getBroadcastItem(i).onWallpaperChanged();
        } catch (RemoteException e) {

            // The RemoteCallbackList will take care of removing
            // the dead object for us.
        }
    }
    wallpaper.callbacks.finishBroadcast();
    final Intent intent = new Intent(Intent.ACTION_WALLPAPER_CHANGED);
    mContext.sendBroadcastAsUser(intent, new UserHandle(mCurrentUserId));
}
 
Example 105
Project: WS171-packages-apps-Music   File: TrackBrowserActivity.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action) ||
            Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)) {
        MusicUtils.setSpinnerState(TrackBrowserActivity.this);
    }
    mReScanHandler.sendEmptyMessage(0);
}
 
Example 106
Project: DemoProject   File: InstallApk.java View source code 6 votes vote down vote up
public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
    intent.setData(Uri.parse(
            "package:com.example.android.helloactivity"));
    intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
    startActivityForResult(intent, REQUEST_UNINSTALL);
}
 
Example 107
Project: dlna   File: YouPlayerFullScreenPlayer.java View source code 6 votes vote down vote up
private void initSdcardStateReceiver() {
    if (null == sdcardEjectReceiver && mContext != null) {
        sdcardEjectReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Intent.ACTION_MEDIA_EJECT.equals(intent.getAction())) {
                    onSdcardEject();
                } 
            }
        };
        
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);
        intentFilter.addAction(Intent.ACTION_MEDIA_EJECT);
        intentFilter.addAction(Intent.ACTION_MEDIA_SHARED);
        intentFilter.addDataScheme("file");
        
        mContext.registerReceiver(sdcardEjectReceiver, intentFilter);
    }
}
 
Example 108
Project: property-db   File: PhoneWindowManager.java View source code 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_DOCK_EVENT.equals(intent.getAction())) {
        mDockMode = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
                Intent.EXTRA_DOCK_STATE_UNDOCKED);
    }
    updateRotation(true);
    updateOrientationListenerLp();
}
 
Example 109
Project: Dashboard   File: MediaActivity.java View source code 6 votes vote down vote up
/**
 * Called when the list of active [email protected] MediaController MediaControllers} changes.
 *
 * @param controllers List of active MediaControllers
 */
@Override
public void onActiveSessionsChanged(List<MediaController> controllers) {
    if (controllers.size() > 0) {

        if (mMediaController != null) {
            if (!controllers.get(0).getSessionToken().equals(mMediaController.getSessionToken())) {
                // Detach current controller
                mMediaController.unregisterCallback(mMediaCallback);
                Log.d("MediaController", "MediaController removed");
                mMediaController = null;

                // Attach new controller
                mMediaController = controllers.get(0);
                mMediaController.registerCallback(mMediaCallback);
                mMediaCallback.onMetadataChanged(mMediaController.getMetadata());
                mMediaCallback.onPlaybackStateChanged(mMediaController.getPlaybackState());
                Log.d("MediaController", "MediaController set: " + mMediaController.getPackageName());
            }
        } else {
            // Attach new controller
            mMediaController = controllers.get(0);
            mMediaController.registerCallback(mMediaCallback);
            mMediaCallback.onMetadataChanged(mMediaController.getMetadata());
            mMediaCallback.onPlaybackStateChanged(mMediaController.getPlaybackState());
            Log.d("MediaController", "MediaController set: " + mMediaController.getPackageName());
        }

        mMediaPlay.setImageTintList(ColorStateList.valueOf(getTheme().obtainStyledAttributes(new int[]{R.attr.cardBackgroundColor}).getColor(0, getResources().getColor(R.color.white))));
    } else {

        mMediaArtist.setText("");
        mMediaAlbum.setText("");
        mMediaTitle.setText(R.string.media_idle);
        mMediaArt.setImageResource(R.drawable.bg_default_album_art);

        Intent i = Intent.makeMainSelectorActivity(Intent.ACTION_MAIN, Intent.CATEGORY_APP_MUSIC);
        PackageManager pm = getPackageManager();
        ResolveInfo info = pm.resolveActivity(i, 0);

        Drawable icon = info.loadIcon(pm);
        mMediaPlay.setPadding(20, 20, 20, 20);
        mMediaPlay.setImageDrawable(icon);

        mMediaPlay.setImageTintList(null);
    }
}
 
Example 110
Project: sawan-bar   File: BluetoothHandsfree.java View source code 6 votes vote down vote up
public BluetoothHandsfree(Context context, CallManager cm) {
    mCM = cm;
    mContext = context;
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    boolean bluetoothCapable = (adapter != null);
    mHeadset = null;  // nothing connected yet
    mA2dp = new BluetoothA2dp(mContext);
    mA2dpState = BluetoothA2dp.STATE_DISCONNECTED;
    mA2dpDevice = null;
    mA2dpSuspended = false;

    mPowerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    mStartCallWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                                                   TAG + ":StartCall");
    mStartCallWakeLock.setReferenceCounted(false);
    mStartVoiceRecognitionWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                                                   TAG + ":VoiceRecognition");
    mStartVoiceRecognitionWakeLock.setReferenceCounted(false);

    mLocalBrsf = BRSF_AG_THREE_WAY_CALLING |
                 BRSF_AG_EC_NR |
                 BRSF_AG_REJECT_CALL |
                 BRSF_AG_ENHANCED_CALL_STATUS;

    if (sVoiceCommandIntent == null) {
        sVoiceCommandIntent = new Intent(Intent.ACTION_VOICE_COMMAND);
        sVoiceCommandIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    if (mContext.getPackageManager().resolveActivity(sVoiceCommandIntent, 0) != null &&
            BluetoothHeadset.isBluetoothVoiceDialingEnabled(mContext)) {
        mLocalBrsf |= BRSF_AG_VOICE_RECOG;
    }

    mBluetoothPhoneState = new BluetoothPhoneState();
    mUserWantsAudio = true;
    mPhonebook = new BluetoothAtPhonebook(mContext, this);
    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    cdmaSetSecondCallState(false);

    if (bluetoothCapable) {
        resetAtState();
    }

}
 
Example 111
Project: property-db   File: ExternalMediaFormatActivity.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Log.d("ExternalMediaFormatActivity", "got action " + action);

    if (action == Intent.ACTION_MEDIA_REMOVED ||
        action == Intent.ACTION_MEDIA_CHECKING ||
        action == Intent.ACTION_MEDIA_MOUNTED ||
        action == Intent.ACTION_MEDIA_SHARED) {
        finish();
    }
}
 
Example 112
Project: dubsar_android   File: CommsReceiver.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	if (intent == null || intent.getAction() == null)
		return;
	
	if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
		// Log.i(context.getString(R.string.app_name), "Boot completed");
	}
	else {
		Log.w(context.getString(R.string.app_name),
				"CommsReceiver ignoring unexpected action " + intent.getAction());
		return;
	}
	
	Intent serviceIntent = new Intent(context, DubsarService.class);
	context.startService(serviceIntent);
}
 
Example 113
Project: guide-app-android   File: GuideMapFragment.java View source code 6 votes vote down vote up
@Override public void onInfoWindowClick(Marker marker) {
  // Since a Marker has no convenient way of attaching metadata to it, we have
  // to keep a reference to it in our map, for this kind of use case.
  Place place = markers.get(marker);

  if (place != null) {
    // Start InfoActivity, closing any activities that are on top it.
    startActivity(
        new Intent(getActivity(), InfoActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
            .putExtra(InfoActivity.EXTRA_PLACE, place));
  }
}
 
Example 114
Project: property-db   File: PackageManagerService.java View source code 6 votes vote down vote up
private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList,
        int uidArr[], IIntentReceiver finishedReceiver) {
    int size = pkgList.size();
    if (size > 0) {
        // Send broadcasts here
        Bundle extras = new Bundle();
        extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
                .toArray(new String[size]));
        if (uidArr != null) {
            extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
        }
        String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
                : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
        sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
    }
}
 
Example 115
Project: property-db   File: Instrumentation.java View source code 6 votes vote down vote up
/**
 * Like [email protected] #execStartActivity(Context, IBinder, IBinder, Activity, Intent, int)},
 * but for calls from a {#link Fragment}.
 * 
 * @param who The Context from which the activity is being started.
 * @param contextThread The main thread of the Context from which the activity
 *                      is being started.
 * @param token Internal token identifying to the system who is starting 
 *              the activity; may be null.
 * @param target Which fragment is performing the start (and thus receiving 
 *               any result).
 * @param intent The actual Intent to start.
 * @param requestCode Identifier for this request's result; less than zero 
 *                    if the caller is not expecting a result.
 * 
 * @return To force the return of a particular result, return an 
 *         ActivityResult object containing the desired data; otherwise
 *         return null.  The default implementation always returns null.
 *  
 * @throws android.content.ActivityNotFoundException
 * 
 * @see Activity#startActivity(Intent)
 * @see Activity#startActivityForResult(Intent, int)
 * @see Activity#startActivityFromChild
 * 
 * [email protected]}
 */
public ActivityResult execStartActivity(
    Context who, IBinder contextThread, IBinder token, Fragment target,
    Intent intent, int requestCode, Bundle options) {
    IApplicationThread whoThread = (IApplicationThread) contextThread;
    if (mActivityMonitors != null) {
        synchronized (mSync) {
            final int N = mActivityMonitors.size();
            for (int i=0; i<N; i++) {
                final ActivityMonitor am = mActivityMonitors.get(i);
                if (am.match(who, null, intent)) {
                    am.mHits++;
                    if (am.isBlocking()) {
                        return requestCode >= 0 ? am.getResult() : null;
                    }
                    break;
                }
            }
        }
    }
    try {
        intent.setAllowFds(false);
        intent.migrateExtraStreamToClipData();
        int result = ActivityManagerNative.getDefault()
            .startActivity(whoThread, intent,
                    intent.resolveTypeIfNeeded(who.getContentResolver()),
                    token, target != null ? target.mWho : null,
                    requestCode, 0, null, null, options);
        checkStartActivityResult(result, intent);
    } catch (RemoteException e) {
    }
    return null;
}
 
Example 116
Project: sawan-bar   File: EmergencyDialer.java View source code 6 votes vote down vote up
/**
 * place the call, but check to make sure it is a viable number.
 */
void placeCall() {
    mLastNumber = mDigits.getText().toString();
    if (PhoneNumberUtils.isEmergencyNumber(mLastNumber)) {
        if (DBG) Log.d(LOG_TAG, "placing call to " + mLastNumber);

        // place the call if it is a valid number
        if (mLastNumber == null || !TextUtils.isGraphic(mLastNumber)) {
            // There is no number entered.
            playTone(ToneGenerator.TONE_PROP_NACK);
            return;
        }
        Intent intent = new Intent(Intent.ACTION_CALL_EMERGENCY);
        intent.setData(Uri.fromParts("tel", mLastNumber, null));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    } else {
        if (DBG) Log.d(LOG_TAG, "rejecting bad requested number " + mLastNumber);

        // erase the number and throw up an alert dialog.
        mDigits.getText().delete(0, mDigits.getText().length());
        showDialog(BAD_EMERGENCY_NUMBER_DIALOG);
    }
}
 
Example 117
Project: wally   File: ImageDetailsActivity.java View source code 6 votes vote down vote up
private void setImageAsWallpaperPicker(Uri path) {
    Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
    intent.setType("image/*");

    MimeTypeMap map = MimeTypeMap.getSingleton();
    String mimeType = map.getMimeTypeFromExtension("png");
    intent.setDataAndType(path, mimeType);
    intent.putExtra("mimeType", mimeType);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    startActivity(Intent.createChooser(intent, getString(R.string.action_set_as)));
}
 
Example 118
Project: property-db   File: AliasActivity.java View source code 6 votes vote down vote up
private Intent parseAlias(XmlPullParser parser)
        throws XmlPullParserException, IOException {
    AttributeSet attrs = Xml.asAttributeSet(parser);
    
    Intent intent = null;
    
    int type;
    while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
            && type != XmlPullParser.START_TAG) {
    }
    
    String nodeName = parser.getName();
    if (!"alias".equals(nodeName)) {
        throw new RuntimeException(
                "Alias meta-data must start with <alias> tag; found"
                + nodeName + " at " + parser.getPositionDescription());
    }
    
    int outerDepth = parser.getDepth();
    while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
           && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
        if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
            continue;
        }

        nodeName = parser.getName();
        if ("intent".equals(nodeName)) {
            Intent gotIntent = Intent.parseIntent(getResources(), parser, attrs);
            if (intent == null) intent = gotIntent;
        } else {
            XmlUtils.skipCurrentTag(parser);
        }
    }
    
    return intent;
}
 
Example 119
Project: jdroid   File: NotificationBuilder.java View source code 6 votes vote down vote up
public void setContentIntentSingleTop(Class<?> clazz, Bundle notificationBundle) {
	Intent notificationIntent = clazz != null ? new Intent(AbstractApplication.get(), clazz) : new Intent();
	if (notificationBundle != null) {
		notificationIntent.replaceExtras(notificationBundle);
	}
	setContentIntentSingleTop(notificationIntent);
}
 
Example 120
Project: WiFi-Automatic   File: UnlockReceiver.java View source code 6 votes vote down vote up
@Override
public void onReceive(final Context context, final Intent intent) {
    final String action = intent.getAction();
    if (Intent.ACTION_USER_PRESENT.equals(action)) {
        context.sendBroadcast(
                new Intent(context, Receiver.class).setAction(USER_PRESENT_ACTION));
    }
}
 
Example 121
Project: devcoin-android   File: BlockchainServiceImpl.java View source code 6 votes vote down vote up
@Override
public void onReceive(final Context context, final Intent intent)
{
	final String action = intent.getAction();

	if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action))
	{
		hasConnectivity = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
		log.info("network is " + (hasConnectivity ? "up" : "down"));

		check();
	}
	else if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action))
	{
		hasStorage = false;
		log.info("device storage low");

		check();
	}
	else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action))
	{
		hasStorage = true;
		log.info("device storage ok");

		check();
	}
}
 
Example 122
Project: property-db   File: PackageManagerService.java View source code 6 votes vote down vote up
private String getRequiredVerifierLPr() {
    final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
    final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
            PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);

    String requiredVerifier = null;

    final int N = receivers.size();
    for (int i = 0; i < N; i++) {
        final ResolveInfo info = receivers.get(i);

        if (info.activityInfo == null) {
            continue;
        }

        final String packageName = info.activityInfo.packageName;

        final PackageSetting ps = mSettings.mPackages.get(packageName);
        if (ps == null) {
            continue;
        }

        if (!ps.grantedPermissions
                .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
            continue;
        }

        if (requiredVerifier != null) {
            throw new RuntimeException("There can be only one required verifier");
        }

        requiredVerifier = packageName;
    }

    return requiredVerifier;
}
 
Example 123
Project: platform_packages_apps_settings   File: InstalledAppDetails.java View source code 6 votes vote down vote up
private void checkForceStop() {
    Intent intent = new Intent(Intent.ACTION_QUERY_PACKAGE_RESTART,
            Uri.fromParts("package", mAppEntry.info.packageName, null));
    intent.putExtra(Intent.EXTRA_PACKAGES, new String[] { mAppEntry.info.packageName });
    intent.putExtra(Intent.EXTRA_UID, mAppEntry.info.uid);
    sendOrderedBroadcast(intent, null, mCheckKillProcessesReceiver, null,
            Activity.RESULT_CANCELED, null, null);
}
 
Example 124
Project: dlna   File: YouPlayerFullScreenPlayer.java View source code 6 votes vote down vote up
private void initTelephoneReceiver() {
    if(getObjectIsNull(mContext)){
    	LOG.e(TAG, "initTelephoneListener", "mView is null");
        return;
    }
    phoneStateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
        	LOG.e(TAG, "initTelephoneReceiver", "action:"+intent.getAction());
            if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL) || intent.getAction().equals("android.intent.action.PHONE_STATE")) {
                if((getPlayerIsLocalAudio() || getPlayerIsOnlineAudio())&& !getPlayerIsPauseStatus() ){
                    onRequestCoreService(You_Core.FN_FULL_SCREEN_BTN_PAUSE, You_Core.FN_UI_EVT_TOUCH_UP, null, 0);
                }
                sendNotification();
            } else {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                if(tm != null){
                    switch (tm.getCallState()) {
                    case TelephonyManager.CALL_STATE_RINGING:
                        if((getPlayerIsLocalAudio() || getPlayerIsOnlineAudio())&& !getPlayerIsPauseStatus() ){
                            onRequestCoreService(You_Core.FN_FULL_SCREEN_BTN_PAUSE, You_Core.FN_UI_EVT_TOUCH_UP, null, null);
                        }
                        sendNotification();
                        break;
                        
                    case TelephonyManager.CALL_STATE_OFFHOOK:
                        break;
                        
                    case TelephonyManager.CALL_STATE_IDLE:
                        break;
                        
                    default:
                        break;
                    }
                }
            }
        }
    };

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
    intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    mContext.registerReceiver(phoneStateReceiver, intentFilter);
}
 
Example 125
Project: property-db   File: NdefRecord.java View source code 6 votes vote down vote up
/**
 * Create a new NDEF Record containing MIME data.<p>
 * Use this method to encode MIME-typed data into an NDEF Record,
 * such as "text/plain", or "image/jpeg".<p>
 * The mimeType parameter will be normalized with
 * [email protected] Intent#normalizeMimeType} to follow Android best
 * practices for intent filtering, for example to force lower-case.
 * However the unchecked exception
 * [email protected] IllegalArgumentException} may be thrown
 * if the mimeType parameter has serious problems,
 * for example if it is empty, so always catch this
 * exception if you are passing user-generated data into this method.
 * <p>
 * For efficiency, This method might not make an internal copy of the
 * mimeData byte array, so take care not
 * to modify the mimeData byte array while still using the returned
 * NdefRecord.
 *
 * @param mimeType a valid MIME type
 * @param mimeData MIME data as bytes
 * @return an NDEF Record containing the MIME-typed data
 * @throws IllegalArugmentException if the mimeType is empty or invalid
 *
 */
public static NdefRecord createMime(String mimeType, byte[] mimeData) {
    if (mimeType == null) throw new NullPointerException("mimeType is null");

    // We only do basic MIME type validation: trying to follow the
    // RFCs strictly only ends in tears, since there are lots of MIME
    // types in common use that are not strictly valid as per RFC rules
    mimeType = Intent.normalizeMimeType(mimeType);
    if (mimeType.length() == 0) throw new IllegalArgumentException("mimeType is empty");
    int slashIndex = mimeType.indexOf('/');
    if (slashIndex == 0) throw new IllegalArgumentException("mimeType must have major type");
    if (slashIndex == mimeType.length() - 1) {
        throw new IllegalArgumentException("mimeType must have minor type");
    }
    // missing '/' is allowed

    // MIME RFCs suggest ASCII encoding for content-type
    byte[] typeBytes = mimeType.getBytes(Charsets.US_ASCII);
    return new NdefRecord(TNF_MIME_MEDIA, typeBytes, null, mimeData);
}
 
Example 126
Project: park-alert   File: TwitterPrepareRequestActivity.java View source code 6 votes vote down vote up
/**
 * Retrieve the OAuth Request Token and present a browser to the user to authorize the token.
 */
@Override
protected Void doInBackground(Void... params) {
	
	try {
		Log.i(TAG, "Retrieving request token from Google servers");
		final String url = provider.retrieveRequestToken(consumer, TwitterUtils.OAUTH_CALLBACK_URL);
		Log.i(TAG, "Popping a browser with the authorize URL : " + url);
		Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_FROM_BACKGROUND);
		context.startActivity(intent);
	} catch (Exception e) {
		Log.e(TAG, "Error during OAUth retrieve request token", e);
	}

	return null;
}
 
Example 127
Project: deb-kitkat-storage-access-framework   File: MainFragment.java View source code 6 votes vote down vote up
/**
 * ????????????
 */
@OnClick(R.id.button_mkdir)
void onMkdirButtonClick() {
    String fileName = String.format("folder-%d", new SecureRandom().nextInt());
    Intent intent = new Intent().setAction(Intent.ACTION_CREATE_DOCUMENT)
                                .addCategory(Intent.CATEGORY_OPENABLE)
                                .setType(DocumentsContract.Document.MIME_TYPE_DIR)
                                .putExtra(Intent.EXTRA_TITLE, fileName);
    startActivityForResult(intent, REQUEST_MKDIR);
}
 
Example 128
Project: property-db   File: PhoneWindowManager.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (Intent.ACTION_USER_SWITCHED.equals(intent.getAction())) {
        // tickle the settings observer: this first ensures that we're
        // observing the relevant settings for the newly-active user,
        // and then updates our own bookkeeping based on the now-
        // current user.
        mSettingsObserver.onChange(false);
    }
}
 
Example 129
Project: HoloDash   File: WidgetClickProxyActivity.java View source code 6 votes vote down vote up
public static Intent wrap(Context context, Intent intent, ComponentName alsoUpdateExtension) {
    return new Intent(context, WidgetClickProxyActivity.class)
            .setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)))
            .putExtra(EXTRA_UPDATE_EXTENSION, (alsoUpdateExtension == null)
                    ? null
                    : alsoUpdateExtension.flattenToString())
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
}
 
Example 130
Project: packages_apps_Launcher2   File: ApplicationInfo.java View source code 6 votes vote down vote up
/**
 * Must not hold the Context.
 */
public ApplicationInfo(ResolveInfo info, IconCache iconCache) {
    this.componentName = new ComponentName(
            info.activityInfo.applicationInfo.packageName,
            info.activityInfo.name);

    this.container = ItemInfo.NO_ID;
    this.setActivity(componentName,
            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

    iconCache.getTitleAndIcon(this, info);
}
 
Example 131
Project: WS171-frameworks-base   File: Settings.java View source code 6 votes vote down vote up
/**
 * Return the title as it should be displayed to the user. This takes
 * care of localizing bookmarks that point to activities.
 * 
 * @param context A context.
 * @param cursor A cursor pointing to the row whose title should be
 *        returned. The cursor must contain at least the [email protected] #TITLE}
 *        and [email protected] #INTENT} columns.
 * @return A title that is localized and can be displayed to the user,
 *         or the empty string if one could not be found.
 */
public static CharSequence getTitle(Context context, Cursor cursor) {
    int titleColumn = cursor.getColumnIndex(TITLE);
    int intentColumn = cursor.getColumnIndex(INTENT);
    if (titleColumn == -1 || intentColumn == -1) {
        throw new IllegalArgumentException(
                "The cursor must contain the TITLE and INTENT columns.");
    }
    
    String title = cursor.getString(titleColumn);
    if (!TextUtils.isEmpty(title)) {
        return title;
    }
    
    String intentUri = cursor.getString(intentColumn);
    if (TextUtils.isEmpty(intentUri)) {
        return "";
    }
    
    Intent intent;
    try {
        intent = Intent.getIntent(intentUri);
    } catch (URISyntaxException e) {
        return "";
    }
    
    PackageManager packageManager = context.getPackageManager();
    ResolveInfo info = packageManager.resolveActivity(intent, 0);
    return info != null ? info.loadLabel(packageManager) : "";
}
 
Example 132
Project: aceim   File: OptionsReceiver.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	OptionKey key = (OptionKey)intent.getParcelableExtra(Constants.INTENT_EXTRA_OPTION_KEY);
	byte serviceId = intent.getByteExtra(Constants.INTENT_EXTRA_SERVICE_ID, (byte) -1);
	
	if (key == null || (key instanceof AccountOptionKeys && serviceId < 0)) {
		Logger.log("OptionsReceiver got broken intent!", LoggerLevel.INFO);
		return;
	}
	
	Object value = intent.getExtras().get(Constants.INTENT_EXTRA_OPTION_VALUE);
	
	for (OnOptionChangedListener listener : mListeners) {
		listener.onOptionChanged(key, value.toString(), serviceId);
	}
}
 
Example 133
Project: property-db   File: ActivityManagerService.java View source code 6 votes vote down vote up
private void forceStopPackageLocked(final String packageName, int uid) {
    forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false,
            false, true, false, UserHandle.getUserId(uid));
    Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
            Uri.fromParts("package", packageName, null));
    if (!mProcessesReady) {
        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
                | Intent.FLAG_RECEIVER_FOREGROUND);
    }
    intent.putExtra(Intent.EXTRA_UID, uid);
    intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid));
    broadcastIntentLocked(null, null, intent,
            null, null, 0, null, null, null,
            false, false,
            MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
}
 
Example 134
Project: GrabSomeFood-Test   File: ActivityCheckout.java View source code 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_checkout);
	
	final Resources res = getResources();
	
	if (Build.VERSION.SDK_INT >= 19) {
		getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
		
		float sSW = res.getConfiguration().smallestScreenWidthDp;
		
		LinearLayout l = (LinearLayout) findViewById(R.id.LParent);
		int statusBarHeight = res.getDimensionPixelSize(res.getIdentifier("status_bar_height", "dimen", "android"));
		int navigationBarHeight = 0;
		
		if (!ViewConfiguration.get(this).hasPermanentMenuKey() && !KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
				&& (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT || sSW > 560)) {
			getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
			navigationBarHeight = res.getDimensionPixelSize(res.getIdentifier("navigation_bar_height", "dimen", "android"));
			FrameLayout nb = (FrameLayout) findViewById(R.id.LNavigationBar);
			nb.setVisibility(View.VISIBLE);
			((FrameLayout.LayoutParams) nb.getLayoutParams()).height = navigationBarHeight;
		}
		
		l.setPadding(0, statusBarHeight, 0, navigationBarHeight);
	}
	
	// http://stackoverflow.com/questions/4790746/links-in-textview
	Linkify.addLinks((TextView) findViewById(R.id.TVCheckoutTitle), Linkify.WEB_URLS);
	Linkify.addLinks((TextView) findViewById(R.id.TVCheckoutText), Linkify.EMAIL_ADDRESSES);
	
	((Button) findViewById(R.id.BGooglePlay)).setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			try {
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getPackageName()))
						.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_MULTIPLE_TASK));
			} catch (ActivityNotFoundException e) {
				e.printStackTrace();
				startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getResources().getString(R.string.google_play_app_site)))
						.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_MULTIPLE_TASK));
			}
		}
	});
}
 
Example 135
Project: property-db   File: UiModeManagerService.java View source code 6 votes vote down vote up
private void updateAfterBroadcastLocked(String action, int enableFlags, int disableFlags) {
    // Launch a dock activity
    String category = null;
    if (UiModeManager.ACTION_ENTER_CAR_MODE.equals(action)) {
        // Only launch car home when car mode is enabled and the caller
        // has asked us to switch to it.
        if (ENABLE_LAUNCH_CAR_DOCK_APP
                && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
            category = Intent.CATEGORY_CAR_DOCK;
        }
    } else if (UiModeManager.ACTION_ENTER_DESK_MODE.equals(action)) {
        // Only launch car home when desk mode is enabled and the caller
        // has asked us to switch to it.  Currently re-using the car
        // mode flag since we don't have a formal API for "desk mode".
        if (ENABLE_LAUNCH_DESK_DOCK_APP
                && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
            category = Intent.CATEGORY_DESK_DOCK;
        }
    } else {
        // Launch the standard home app if requested.
        if ((disableFlags & UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
            category = Intent.CATEGORY_HOME;
        }
    }

    if (LOG) {
        Slog.v(TAG, String.format(
            "Handling broadcast result for action %s: enable=0x%08x, disable=0x%08x, "
                + "category=%s",
            action, enableFlags, disableFlags, category));
    }

    sendConfigurationAndStartDreamOrDockAppLocked(category);
}
 
Example 136
Project: property-db   File: ActivityManagerService.java View source code 6 votes vote down vote up
/**
 * Starts the "new version setup screen" if appropriate.
 */
void startSetupActivityLocked() {
    // Only do this once per boot.
    if (mCheckedForSetup) {
        return;
    }
    
    // We will show this screen if the current one is a different
    // version than the last one shown, and we are not running in
    // low-level factory test mode.
    final ContentResolver resolver = mContext.getContentResolver();
    if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
            Settings.Global.getInt(resolver,
                    Settings.Global.DEVICE_PROVISIONED, 0) != 0) {
        mCheckedForSetup = true;
        
        // See if we should be showing the platform update setup UI.
        Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
        List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
                .queryIntentActivities(intent, PackageManager.GET_META_DATA);
        
        // We don't allow third party apps to replace this.
        ResolveInfo ri = null;
        for (int i=0; ris != null && i<ris.size(); i++) {
            if ((ris.get(i).activityInfo.applicationInfo.flags
                    & ApplicationInfo.FLAG_SYSTEM) != 0) {
                ri = ris.get(i);
                break;
            }
        }
        
        if (ri != null) {
            String vers = ri.activityInfo.metaData != null
                    ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
                    : null;
            if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
                vers = ri.activityInfo.applicationInfo.metaData.getString(
                        Intent.METADATA_SETUP_VERSION);
            }
            String lastVers = Settings.Secure.getString(
                    resolver, Settings.Secure.LAST_SETUP_SHOWN);
            if (vers != null && !vers.equals(lastVers)) {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setComponent(new ComponentName(
                        ri.activityInfo.packageName, ri.activityInfo.name));
                mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
                        null, null, 0, 0, 0, 0, null, false, null);
            }
        }
    }
}
 
Example 137
Project: android-voip-service   File: IncallActivity.java View source code 6 votes vote down vote up
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
	if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
		startActivity(new Intent()
		.setAction(Intent.ACTION_MAIN)
		.addCategory(Intent.CATEGORY_HOME));
		return true;
	} else {
		return super.onKeyUp(keyCode, event);
	}
}
 
Example 138
Project: property-db   File: ApplicationPackageManager.java View source code 6 votes vote down vote up
@Override
public Intent getLaunchIntentForPackage(String packageName) {
    // First see if the package has an INFO activity; the existence of
    // such an activity is implied to be the desired front-door for the
    // overall package (such as if it has multiple launcher entries).
    Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
    intentToResolve.addCategory(Intent.CATEGORY_INFO);
    intentToResolve.setPackage(packageName);
    List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0);

    // Otherwise, try to find a main launcher activity.
    if (ris == null || ris.size() <= 0) {
        // reuse the intent instance
        intentToResolve.removeCategory(Intent.CATEGORY_INFO);
        intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
        intentToResolve.setPackage(packageName);
        ris = queryIntentActivities(intentToResolve, 0);
    }
    if (ris == null || ris.size() <= 0) {
        return null;
    }
    Intent intent = new Intent(intentToResolve);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setClassName(ris.get(0).activityInfo.packageName,
            ris.get(0).activityInfo.name);
    return intent;
}
 
Example 139
Project: sdk-support   File: RemoteInputCompatJellybean.java View source code 6 votes vote down vote up
static void addResultsToIntent(RemoteInputCompatBase.RemoteInput[] remoteInputs, Intent intent,
        Bundle results) {
    Bundle resultsBundle = new Bundle();
    for (RemoteInputCompatBase.RemoteInput remoteInput : remoteInputs) {
        Object result = results.get(remoteInput.getResultKey());
        if (result instanceof CharSequence) {
            resultsBundle.putCharSequence(remoteInput.getResultKey(), (CharSequence) result);
        }
    }
    Intent clipIntent = new Intent();
    clipIntent.putExtra(EXTRA_RESULTS_DATA, resultsBundle);
    intent.setClipData(ClipData.newIntent(RESULTS_CLIP_LABEL, clipIntent));
}
 
Example 140
Project: property-db   File: DeviceStorageMonitorService.java View source code 6 votes vote down vote up
/**
* This method sends a notification to NotificationManager to display
* an error dialog indicating low disk space and launch the Installer
* application
*/
private final void sendNotification() {
    if(localLOGV) Slog.i(TAG, "Sending low memory notification");
    //log the event to event log with the amount of free storage(in bytes) left on the device
    EventLog.writeEvent(EventLogTags.LOW_STORAGE, mFreeMem);
    //  Pack up the values and broadcast them to everyone
    Intent lowMemIntent = new Intent(Environment.isExternalStorageEmulated()
            ? Settings.ACTION_INTERNAL_STORAGE_SETTINGS
            : Intent.ACTION_MANAGE_PACKAGE_STORAGE);
    lowMemIntent.putExtra("memory", mFreeMem);
    lowMemIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    NotificationManager mNotificationMgr =
            (NotificationManager)mContext.getSystemService(
                    Context.NOTIFICATION_SERVICE);
    CharSequence title = mContext.getText(
            com.android.internal.R.string.low_internal_storage_view_title);
    CharSequence details = mContext.getText(
            com.android.internal.R.string.low_internal_storage_view_text);
    PendingIntent intent = PendingIntent.getActivityAsUser(mContext, 0,  lowMemIntent, 0,
            null, UserHandle.CURRENT);
    Notification notification = new Notification();
    notification.icon = com.android.internal.R.drawable.stat_notify_disk_full;
    notification.tickerText = title;
    notification.flags |= Notification.FLAG_NO_CLEAR;
    notification.setLatestEventInfo(mContext, title, details, intent);
    mNotificationMgr.notifyAsUser(null, LOW_MEMORY_NOTIFICATION_ID, notification,
            UserHandle.ALL);
    mContext.sendStickyBroadcastAsUser(mStorageLowIntent, UserHandle.ALL);
}
 
Example 141
Project: AndroidArch   File: IntentHelper.java View source code 6 votes vote down vote up
public static char getCharExtra(@Nullable Intent intent, @NonNull String key,
        char defValue) {
    if (intent == null) {
        return defValue;
    }

    try {
        return intent.getCharExtra(key, defValue);
    } catch (Exception e) {
        onIntentAttacked(intent, e);
    }
    return defValue;
}
 
Example 142
Project: open-bixi-gpstracker   File: ExportGPXTest.java View source code 6 votes vote down vote up
@SmallTest
public void testIntentCreation()
{
   ContentResolver resolver = new MockContentResolver();

   Uri uri = ContentUris.withAppendedId( Tracks.CONTENT_URI, 0 );
   Intent actionIntent = new Intent(Intent.ACTION_RUN, uri );
   actionIntent.setDataAndType( uri, Tracks.CONTENT_ITEM_TYPE );
   actionIntent.addFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION );
   
   // Action match
   Assert.assertEquals( "Action", actionIntent.getAction(), Intent.ACTION_RUN  );
   
   // Category match
   Assert.assertEquals( "Category", actionIntent.getCategories(), null );
   
   // Data match
   Assert.assertEquals( "Mock Infered Data Type", Tracks.CONTENT_ITEM_TYPE, actionIntent.resolveType( resolver ) );
   Assert.assertEquals( "Mock Data Type", Tracks.CONTENT_ITEM_TYPE, actionIntent.getType() ) ;
   
   Assert.assertEquals( "Data Schema", "content", actionIntent.getScheme() );
   Assert.assertEquals( "Data Authority", "nl.sogeti.android.gpstracker", actionIntent.getData().getAuthority() );
   Assert.assertEquals( "Data Path", "/tracks/0", actionIntent.getData().getPath() );
}
 
Example 143
Project: HoloDash   File: HoloDashActivity.java View source code 6 votes vote down vote up
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent clickIntent = new Intent(this, WidgetClickProxyActivity.class);
    clickIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);

    ExtensionManager.ExtensionWithData extension = (ExtensionManager.ExtensionWithData) extensionsAdapter.getItem(position);
    Intent extensionIntent = extension.latestData.clickIntent();

    Intent fillInIntent = WidgetClickProxyActivity.getFillIntent(extensionIntent, extension.listing.componentName);
    clickIntent.fillIn(fillInIntent, Intent.FILL_IN_DATA);
    startActivity(clickIntent);
}
 
Example 144
Project: TeleportR   File: Main.java View source code 6 votes vote down vote up
@Override
	protected void onStart() {
		super.onStart();
//		Log.d(Teleporter.TAG, "onStart");
		registerReceiver(timetick, new IntentFilter(Intent.ACTION_TIME_TICK));
		getContentResolver().registerContentObserver(Ride.URI, false, refresh);
	}
 
Example 145
Project: Nimingban   File: SettingsActivity.java View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void openDirPickerL() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
    try {
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE_DIR_L);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(getActivity(), R.string.em_cant_find_activity, Toast.LENGTH_SHORT).show();
    }
}
 
Example 146
Project: property-db   File: GsmServiceStateTracker.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_LOCALE_CHANGED)) {
        // update emergency string whenever locale changed
        updateSpnDisplay();
    }
}
 
Example 147
Project: flybook   File: BookDownloader.java View source code 6 votes vote down vote up
public void onCreate(Bundle icicle) {
	super.onCreate(icicle);

	Thread.setDefaultUncaughtExceptionHandler(new org.geometerplus.zlibrary.ui.androidfly.library.UncaughtExceptionHandler(this));

	final Intent intent = getIntent();
	Uri uri = intent.getData();
	intent.setData(null);
	if (uri == null || !acceptsUri(uri)) {
		finish();
		return;
	}

	if (!intent.hasExtra(BookDownloaderService.SHOW_NOTIFICATIONS_KEY)) {
		intent.putExtra(BookDownloaderService.SHOW_NOTIFICATIONS_KEY, 
			BookDownloaderService.Notifications.ALREADY_DOWNLOADING);
	}
	if ("epub".equals(uri.getScheme())) {
		uri = uri.buildUpon().scheme("http").build();
		intent.putExtra(BookDownloaderService.BOOK_FORMAT_KEY,
				BookReference.Format.EPUB);
	}

	startService(
		new Intent(Intent.ACTION_DEFAULT, uri, this, BookDownloaderService.class)
			.putExtras(intent.getExtras())
	);
	finish();
}
 
Example 148
Project: p1keyboard   File: BluezIME.java View source code 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
	String sid = intent.getStringExtra(BluezService.SESSION_ID);
	if (sid == null || !sid.startsWith(SESSION_ID))
		return;
	

	if (D) Log.d(LOG_NAME, "Update event received");
	
	try {
		int controllerNo = Integer.parseInt(sid.substring(SESSION_ID.length()));

		InputConnection ic = getCurrentInputConnection();
		long eventTime = SystemClock.uptimeMillis();

		if (intent.getAction().equals(BluezService.EVENT_KEYPRESS)) {
			int action = intent.getIntExtra(BluezService.EVENT_KEYPRESS_ACTION, KeyEvent.ACTION_DOWN);
			int key = intent.getIntExtra(BluezService.EVENT_KEYPRESS_KEY, 0);
			int metakey = intent.getIntExtra(BluezService.EVENT_KEYPRESS_MODIFIERS, 0);
			int special = intent.getIntExtra(BluezService.EVENT_KEYPRESS_SPECIAL, 0);
			
			if (special > 0) {
				switch(special) {
				case BluezService.SPECIAL_COPY:
					ic.performContextMenuAction(android.R.id.copy);
					break;
				case BluezService.SPECIAL_CUT:
					ic.performContextMenuAction(android.R.id.cut);
					break;
				case BluezService.SPECIAL_PASTE:
					ic.performContextMenuAction(android.R.id.paste);
					break;
				case BluezService.SPECIAL_SELECT_ALL:
					ic.performContextMenuAction(android.R.id.selectAll);
					break;
				case BluezService.SPECIAL_HOME:
					Intent i = new Intent(Intent.ACTION_MAIN);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					i.addCategory(Intent.CATEGORY_HOME);
					startActivity(i);
					break;
				case BluezService.SPECIAL_UNICODE:
					ic.commitText(String.valueOf(Character.toChars(key)),1 );
				}
				
				return;
			}

			//This construct ensures that we can perform lock free
			// access to m_keyMappingCache and never risk sending -1 
			// as the keyCode
			if (controllerNo >= m_keyMappingCache.length || key >= m_keyMappingCache[controllerNo].length) {
				Log.e(LOG_NAME, "Key reported by driver: " + key + ", size of keymapping array: " + m_keyMappingCache[0].length + ", controller no " + controllerNo + ", expected controllers: " + m_keyMappingCache.length);
			} else {
				int translatedKey = m_keyMappingCache[controllerNo][key];
				if (translatedKey == -1) {
					translatedKey = m_prefs.getKeyMapping(key, controllerNo);
					m_keyMappingCache[controllerNo][key] = translatedKey;
				}
				
				//TODO: This conflicts slightly with keyboard, because we have no way of knowing.
				// if the mapping is deliberately without a meta key, or just default.
				//So if we have a case where the controller sends a meta modifier, we
				// do not apply the user chosen override.
				//Currently this is not a problem, because only the keyboard HID sends the modifier,
				// and the user cannot set the modifier anyway
				if (metakey == 0) {
					metakey = m_metaKeyMappingCache[controllerNo][key];
					if (metakey == -1) {
						metakey = m_prefs.getMetaKeyMapping(key, controllerNo);
						m_metaKeyMappingCache[controllerNo][key] = metakey;
					}
				}

				if (D) Log.d(LOG_NAME, "Sending key event: " + (action == KeyEvent.ACTION_DOWN ? "Down" : "Up") + " - " + key + " - " + metakey);
				ic.sendKeyEvent(new KeyEvent(eventTime, eventTime, action, translatedKey, 0, metakey, 0, 0, KeyEvent.FLAG_SOFT_KEYBOARD));
			}
		}
	} catch (Exception ex) {
		Log.e(LOG_NAME, "Failed to send key events: " + ex.toString());
	}
}
 
Example 149
Project: BioWiki   File: EditPostContentFragment.java View source code 5 votes vote down vote up
private void handleMediaGalleryResult(Intent data) {
    MediaGallery gallery = (MediaGallery) data.getSerializableExtra(MediaGalleryActivity.RESULT_MEDIA_GALLERY);

    // if blank gallery returned, don't add to span
    if (gallery == null || gallery.getIds().size() == 0)
        return;


    int selectionStart = mContentEditText.getSelectionStart();
    int selectionEnd = mContentEditText.getSelectionEnd();

    if (selectionStart > selectionEnd) {
        int temp = selectionEnd;
        selectionEnd = selectionStart;
        selectionStart = temp;
    }

    int line, column = 0;
    if (mContentEditText.getLayout() != null) {
        line = mContentEditText.getLayout().getLineForOffset(selectionStart);
        column = mContentEditText.getSelectionStart() - mContentEditText.getLayout().getLineStart(line);
    }

    Editable s = mContentEditText.getText();
    if (s == null)
        return;
    MediaGalleryImageSpan[] gallerySpans = s.getSpans(selectionStart, selectionEnd, MediaGalleryImageSpan.class);
    if (gallerySpans.length != 0) {
        for (MediaGalleryImageSpan gallerySpan : gallerySpans) {
            if (gallerySpan.getMediaGallery().getUniqueId() == gallery.getUniqueId()) {
                // replace the existing span with a new gallery, re-add it to the same position.
                gallerySpan.setMediaGallery(gallery);
                int spanStart = s.getSpanStart(gallerySpan);
                int spanEnd = s.getSpanEnd(gallerySpan);
                s.setSpan(gallerySpan, spanStart, spanEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return;
    } else if (column != 0) {
        // insert one line break if the cursor is not at the first column
        s.insert(selectionEnd, "\n");
        selectionStart = selectionStart + 1;
        selectionEnd = selectionEnd + 1;
    }

    s.insert(selectionStart, " ");
    MediaGalleryImageSpan is = new MediaGalleryImageSpan(getActivity(), gallery);
    s.setSpan(is, selectionStart, selectionEnd + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    AlignmentSpan.Standard as = new AlignmentSpan.Standard(Layout.Alignment.ALIGN_CENTER);
    s.setSpan(as, selectionStart, selectionEnd + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    s.insert(selectionEnd + 1, "\n\n");
}
 
Example 150
Project: AmazeFileManager   File: MainActivity.java View source code 5 votes vote down vote up
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
        if (requestCode == 3) {
            String p = Sp.getString("URI", null);
            Uri oldUri = null;
            if (p != null) oldUri = Uri.parse(p);
            Uri treeUri = null;
            if (responseCode == Activity.RESULT_OK) {
                // Get Uri from Storage Access Framework.
                treeUri = intent.getData();
                // Persist URI - this is required for verification of writability.
                if (treeUri != null) Sp.edit().putString("URI", treeUri.toString()).commit();
            }

            // If not confirmed SAF, or if still not writable, then revert settings.
            if (responseCode != Activity.RESULT_OK) {
               /* DialogUtil.displayError(getActivity(), R.string.message_dialog_cannot_write_to_folder_saf, false,
                        currentFolder);||!FileUtil.isWritableNormalOrSaf(currentFolder)
*/
                if (treeUri != null) Sp.edit().putString("URI", oldUri.toString()).commit();
                return;
            }

            // After confirmation, update stored value of folder.
            // Persist access permissions.
            final int takeFlags = intent.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            getContentResolver().takePersistableUriPermission(treeUri, takeFlags);
            switch (operation) {
                case DELETE://deletion
                    new DeleteTask(null, mainActivity).execute((oparrayList));
                    break;
                case COPY://copying
                    Intent intent1 = new Intent(con, CopyService.class);
                    intent1.putExtra("FILE_PATHS", (oparrayList));
                    intent1.putExtra("COPY_DIRECTORY", oppathe);
                    startService(intent1);
                    break;
                case MOVE://moving
                    new MoveFiles(utils.toFileArray(oparrayList), ((Main) getFragment().getTab()), ((Main) getFragment().getTab()).getActivity()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, path);
                    break;
                case NEW_FOLDER://mkdir
                    Main ma1 = ((Main) getFragment().getTab());
                    mkDir((oppathe), ma1);
                    break;
                case RENAME:
                    rename((oppathe), (oppathe1));
                    Main ma2 = ((Main) getFragment().getTab());
                    ma2.updateList();
                    break;
                case NEW_FILE:
                    Main ma3 = ((Main) getFragment().getTab());
                    mkFile((oppathe), ma3);

                    break;
                case EXTRACT:
                    extractFile(new File(oppathe));
                    break;
                case COMPRESS:
                    compressFiles(new File(oppathe), oparrayList);
            }
        }
    }
 
Example 151
Project: hci-2011-2   File: LocalBroadcastManager.java View source code 5 votes vote down vote up
/**
 * Broadcast the given intent to all interested BroadcastReceivers.  This
 * call is asynchronous; it returns immediately, and you will continue
 * executing while the receivers are run.
 *
 * @param intent The Intent to broadcast; all receivers matching this
 *     Intent will receive the broadcast.
 *
 * @see #registerReceiver
 */
public boolean sendBroadcast(Intent intent) {
    synchronized (mReceivers) {
        final String action = intent.getAction();
        final String type = intent.resolveTypeIfNeeded(
                mAppContext.getContentResolver());
        final Uri data = intent.getData();
        final String scheme = intent.getScheme();
        final Set<String> categories = intent.getCategories();

        final boolean debug = DEBUG ||
                ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
        if (debug) Log.v(
                TAG, "Resolving type " + type + " scheme " + scheme
                + " of intent " + intent);

        ArrayList<ReceiverRecord> entries = mActions.get(intent.getAction());
        if (entries != null) {
            if (debug) Log.v(TAG, "Action list: " + entries);

            ArrayList<ReceiverRecord> receivers = null;
            for (int i=0; i<entries.size(); i++) {
                ReceiverRecord receiver = entries.get(i);
                if (debug) Log.v(TAG, "Matching against filter " + receiver.filter);

                if (receiver.broadcasting) {
                    if (debug) {
                        Log.v(TAG, "  Filter's target already added");
                    }
                    continue;
                }

                int match = receiver.filter.match(action, type, scheme, data,
                        categories, "LocalBroadcastManager");
                if (match >= 0) {
                    if (debug) Log.v(TAG, "  Filter matched!  match=0x" +
                            Integer.toHexString(match));
                    if (receivers == null) {
                        receivers = new ArrayList<ReceiverRecord>();
                    }
                    receivers.add(receiver);
                    receiver.broadcasting = true;
                } else {
                    if (debug) {
                        String reason;
                        switch (match) {
                            case IntentFilter.NO_MATCH_ACTION: reason = "action"; break;
                            case IntentFilter.NO_MATCH_CATEGORY: reason = "category"; break;
                            case IntentFilter.NO_MATCH_DATA: reason = "data"; break;
                            case IntentFilter.NO_MATCH_TYPE: reason = "type"; break;
                            default: reason = "unknown reason"; break;
                        }
                        Log.v(TAG, "  Filter did not match: " + reason);
                    }
                }
            }

            if (receivers != null) {
                for (int i=0; i<receivers.size(); i++) {
                    receivers.get(i).broadcasting = false;
                }
                mPendingBroadcasts.add(new BroadcastRecord(intent, receivers));
                if (!mHandler.hasMessages(MSG_EXEC_PENDING_BROADCASTS)) {
                    mHandler.sendEmptyMessage(MSG_EXEC_PENDING_BROADCASTS);
                }
                return true;
            }
        }
    }
    return false;
}
 
Example 152
Project: climbers   File: MapsActivity.java View source code 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_maps);
	getActionBar().setDisplayHomeAsUpEnabled(true);

	mMap = ((MapFragment) getFragmentManager().findFragmentById(
			R.id.map)).getMap();
	seekBar = (SeekBar) findViewById(R.id.seekBarRadius);

	mMap.setMyLocationEnabled(true);

	seekBarListener = new MySeekBarChangeListener();
	seekBar.setOnSeekBarChangeListener(seekBarListener);

	MapClickListener clickListener = new MapClickListener(mMap, seekBarListener, this);
	mMap.setOnMapClickListener(clickListener);

	Criteria criteria = new Criteria();
	LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
	String provider = locationManager.getBestProvider(criteria, false);

	if(savedInstanceState != null)
	{
		position = new LatLng(savedInstanceState.getDouble(StringConstants.LAT), savedInstanceState.getDouble(StringConstants.LNG));
		radius = savedInstanceState.getDouble(StringConstants.RADIUS);
	}
	else
	{
		Location location = locationManager.getLastKnownLocation(provider);
		double lat =  location.getLatitude();
		double lng = location.getLongitude();
		Intent intent = getIntent();
		lat = intent.getDoubleExtra(StringConstants.LAT, lat);
		lng = intent.getDoubleExtra(StringConstants.LNG, lng);
		radius = intent.getDoubleExtra(StringConstants.RADIUS, 1000);
		position = new LatLng(lat, lng);
	}

	CircleOptions circleOptions = new CircleOptions()
	.center(position)
	.radius(radius)
	.strokeWidth(2).strokeColor(Color.BLUE)
	.fillColor(Color.parseColor("#500084d3"));

	Circle circle = mMap.addCircle(circleOptions);
	seekBarListener.setCircle(circle);

	CameraPosition cameraPosition = new CameraPosition.Builder()
	.target(position)
	.zoom(11)
	.build();
	mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
 
Example 153
Project: packages_apps_Launcher2   File: Launcher.java View source code 5 votes vote down vote up
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
        mSharedPrefs.registerOnSharedPreferenceChangeListener(this);

        LauncherApplication app = ((LauncherApplication)getApplication());
        mModel = app.setLauncher(this);
        mIconCache = app.getIconCache();
        mDragController = new DragController(this);
        mInflater = getLayoutInflater();

        mAppWidgetManager = AppWidgetManager.getInstance(this);
        mAppWidgetHost = new LauncherAppWidgetHost(this, APPWIDGET_HOST_ID);
        mAppWidgetHost.startListening();

        if (PROFILE_STARTUP) {
            android.os.Debug.startMethodTracing(
                    Environment.getExternalStorageDirectory() + "/launcher");
        }

	loadHotseats();
        checkForLocaleChange();
        setWallpaperDimension();

// Sets the number of screens replaces setContentView(R.layout.launcher)
        setNumScreens();
        setupViews();

        registerContentObservers();

        lockAllApps();

        mSavedState = savedInstanceState;
        restoreState(mSavedState);

        if (PROFILE_STARTUP) {
            android.os.Debug.stopMethodTracing();
        }

        if (!mRestoring) {
            mModel.startLoader(this, true);
        }

        // For handling default keys
        mDefaultKeySsb = new SpannableStringBuilder();
        Selection.setSelection(mDefaultKeySsb, 0);

        IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(mCloseSystemDialogsReceiver, filter);

    }
 
Example 154
Project: SealBrowser   File: SelectFileDialog.java View source code 5 votes vote down vote up
/**
 * Creates and starts an intent based on the passed fileTypes and capture value.
 * @param fileTypes MIME types requested (i.e. "image/*")
 * @param capture The capture value as described in http://www.w3.org/TR/html-media-capture/
 * @param window The WindowAndroid that can show intents
 */
@CalledByNative
private void selectFile(String[] fileTypes, boolean capture, WindowAndroid window) {
    mFileTypes = new ArrayList<String>(Arrays.asList(fileTypes));
    mCapture = capture;

    Intent chooser = new Intent(Intent.ACTION_CHOOSER);
    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    mCameraOutputUri = Uri.fromFile(getFileForImageCapture());
    camera.putExtra(MediaStore.EXTRA_OUTPUT, mCameraOutputUri);
    Intent camcorder = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
    Intent soundRecorder = new Intent(
            MediaStore.Audio.Media.RECORD_SOUND_ACTION);

    // Quick check - if the |capture| parameter is set and |fileTypes| has the appropriate MIME
    // type, we should just launch the appropriate intent. Otherwise build up a chooser based on
    // the accept type and then display that to the user.
    if (captureCamera()) {
        if (window.showIntent(camera, this, R.string.low_memory_error)) return;
    } else if (captureCamcorder()) {
        if (window.showIntent(camcorder, this, R.string.low_memory_error)) return;
    } else if (captureMicrophone()) {
        if (window.showIntent(soundRecorder, this, R.string.low_memory_error)) return;
    }

    Intent getContentIntent = new Intent(Intent.ACTION_GET_CONTENT);
    getContentIntent.addCategory(Intent.CATEGORY_OPENABLE);
    ArrayList<Intent> extraIntents = new ArrayList<Intent>();
    if (!noSpecificType()) {
        // Create a chooser based on the accept type that was specified in the webpage. Note
        // that if the web page specified multiple accept types, we will have built a generic
        // chooser above.
        if (shouldShowImageTypes()) {
            extraIntents.add(camera);
            getContentIntent.setType(ALL_IMAGE_TYPES);
        } else if (shouldShowVideoTypes()) {
            extraIntents.add(camcorder);
            getContentIntent.setType(ALL_VIDEO_TYPES);
        } else if (shouldShowAudioTypes()) {
            extraIntents.add(soundRecorder);
            getContentIntent.setType(ALL_AUDIO_TYPES);
        }
    }

    if (extraIntents.isEmpty()) {
        // We couldn't resolve an accept type, so fallback to a generic chooser.
        getContentIntent.setType(ANY_TYPES);
        extraIntents.add(camera);
        extraIntents.add(camcorder);
        extraIntents.add(soundRecorder);
    }

    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS,
            extraIntents.toArray(new Intent[] { }));

    chooser.putExtra(Intent.EXTRA_INTENT, getContentIntent);

    if (!window.showIntent(chooser, this, R.string.low_memory_error)) {
        onFileNotSelected();
    }
}
 
Example 155
Project: property-db   File: UiModeManagerService.java View source code 5 votes vote down vote up
private void updateLocked(int enableFlags, int disableFlags) {
    String action = null;
    String oldAction = null;
    if (mLastBroadcastState == Intent.EXTRA_DOCK_STATE_CAR) {
        adjustStatusBarCarModeLocked();
        oldAction = UiModeManager.ACTION_EXIT_CAR_MODE;
    } else if (isDeskDockState(mLastBroadcastState)) {
        oldAction = UiModeManager.ACTION_EXIT_DESK_MODE;
    }

    if (mCarModeEnabled) {
        if (mLastBroadcastState != Intent.EXTRA_DOCK_STATE_CAR) {
            adjustStatusBarCarModeLocked();

            if (oldAction != null) {
                mContext.sendBroadcastAsUser(new Intent(oldAction), UserHandle.ALL);
            }
            mLastBroadcastState = Intent.EXTRA_DOCK_STATE_CAR;
            action = UiModeManager.ACTION_ENTER_CAR_MODE;
        }
    } else if (isDeskDockState(mDockState)) {
        if (!isDeskDockState(mLastBroadcastState)) {
            if (oldAction != null) {
                mContext.sendBroadcastAsUser(new Intent(oldAction), UserHandle.ALL);
            }
            mLastBroadcastState = mDockState;
            action = UiModeManager.ACTION_ENTER_DESK_MODE;
        }
    } else {
        mLastBroadcastState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
        action = oldAction;
    }

    if (action != null) {
        if (LOG) {
            Slog.v(TAG, String.format(
                "updateLocked: preparing broadcast: action=%s enable=0x%08x disable=0x%08x",
                action, enableFlags, disableFlags));
        }

        // Send the ordered broadcast; the result receiver will receive after all
        // broadcasts have been sent. If any broadcast receiver changes the result
        // code from the initial value of RESULT_OK, then the result receiver will
        // not launch the corresponding dock application. This gives apps a chance
        // to override the behavior and stay in their app even when the device is
        // placed into a dock.
        Intent intent = new Intent(action);
        intent.putExtra("enableFlags", enableFlags);
        intent.putExtra("disableFlags", disableFlags);
        mContext.sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null,
                mResultReceiver, null, Activity.RESULT_OK, null, null);

        // Attempting to make this transition a little more clean, we are going
        // to hold off on doing a configuration change until we have finished
        // the broadcast and started the home activity.
        mHoldingConfiguration = true;
        updateConfigurationLocked();
    } else {
        String category = null;
        if (mCarModeEnabled) {
            if (ENABLE_LAUNCH_CAR_DOCK_APP
                    && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
                category = Intent.CATEGORY_CAR_DOCK;
            }
        } else if (isDeskDockState(mDockState)) {
            if (ENABLE_LAUNCH_DESK_DOCK_APP
                    && (enableFlags & UiModeManager.ENABLE_CAR_MODE_GO_CAR_HOME) != 0) {
                category = Intent.CATEGORY_DESK_DOCK;
            }
        } else {
            if ((disableFlags & UiModeManager.DISABLE_CAR_MODE_GO_HOME) != 0) {
                category = Intent.CATEGORY_HOME;
            }
        }

        if (LOG) {
            Slog.v(TAG, "updateLocked: null action, mDockState="
                    + mDockState +", category=" + category);
        }

        sendConfigurationAndStartDreamOrDockAppLocked(category);
    }

    // keep screen on when charging and in car mode
    boolean keepScreenOn = mCharging &&
            ((mCarModeEnabled && mCarModeKeepsScreenOn) ||
             (mCurUiMode == Configuration.UI_MODE_TYPE_DESK && mDeskModeKeepsScreenOn));
    if (keepScreenOn != mWakeLock.isHeld()) {
        if (keepScreenOn) {
            mWakeLock.acquire();
        } else {
            mWakeLock.release();
        }
    }
}
 
Example 156
Project: property-db   File: MountService.java View source code 5 votes vote down vote up
private int doMountVolume(String path) {
    int rc = StorageResultCode.OperationSucceeded;

    final StorageVolume volume;
    synchronized (mVolumesLock) {
        volume = mVolumesByPath.get(path);
    }

    if (DEBUG_EVENTS) Slog.i(TAG, "doMountVolume: Mouting " + path);
    try {
        mConnector.execute("volume", "mount", path);
    } catch (NativeDaemonConnectorException e) {
        /*
         * Mount failed for some reason
         */
        String action = null;
        int code = e.getCode();
        if (code == VoldResponseCode.OpFailedNoMedia) {
            /*
             * Attempt to mount but no media inserted
             */
            rc = StorageResultCode.OperationFailedNoMedia;
        } else if (code == VoldResponseCode.OpFailedMediaBlank) {
            if (DEBUG_EVENTS) Slog.i(TAG, " updating volume state :: media nofs");
            /*
             * Media is blank or does not contain a supported filesystem
             */
            updatePublicVolumeState(volume, Environment.MEDIA_NOFS);
            action = Intent.ACTION_MEDIA_NOFS;
            rc = StorageResultCode.OperationFailedMediaBlank;
        } else if (code == VoldResponseCode.OpFailedMediaCorrupt) {
            if (DEBUG_EVENTS) Slog.i(TAG, "updating volume state media corrupt");
            /*
             * Volume consistency check failed
             */
            updatePublicVolumeState(volume, Environment.MEDIA_UNMOUNTABLE);
            action = Intent.ACTION_MEDIA_UNMOUNTABLE;
            rc = StorageResultCode.OperationFailedMediaCorrupt;
        } else {
            rc = StorageResultCode.OperationFailedInternalError;
        }

        /*
         * Send broadcast intent (if required for the failure)
         */
        if (action != null) {
            sendStorageIntent(action, volume, UserHandle.ALL);
        }
    }

    return rc;
}
 
Example 157
Project: platform_packages_apps_settings   File: PowerUsageDetail.java View source code 5 votes vote down vote up
private void createDetails() {
    final Intent intent = getIntent();
    mTitle = intent.getStringExtra(EXTRA_TITLE);
    final int percentage = intent.getIntExtra(EXTRA_PERCENT, 1);
    final int gaugeValue = intent.getIntExtra(EXTRA_GAUGE, 1);
    mUsageSince = intent.getIntExtra(EXTRA_USAGE_SINCE, USAGE_SINCE_UNPLUGGED);
    mUid = intent.getIntExtra(EXTRA_UID, 0);
    mDrainType = (DrainType) intent.getSerializableExtra(EXTRA_DRAIN_TYPE);
    mNoCoverage = intent.getDoubleExtra(EXTRA_NO_COVERAGE, 0);
    String iconPackage = intent.getStringExtra(EXTRA_ICON_PACKAGE);
    int iconId = intent.getIntExtra(EXTRA_ICON_ID, 0);
    if (!TextUtils.isEmpty(iconPackage)) {
        try {
            final PackageManager pm = getPackageManager();
            ApplicationInfo ai = pm.getPackageInfo(iconPackage, 0).applicationInfo;
            if (ai != null) {
                mAppIcon = ai.loadIcon(pm);
            }
        } catch (NameNotFoundException nnfe) {
            // Use default icon
        }
    } else if (iconId != 0) {
        mAppIcon = getResources().getDrawable(iconId);
    }
    if (mAppIcon == null) {
        mAppIcon = getPackageManager().getDefaultActivityIcon();
    }

    // Set the description
    String summary = getDescriptionForDrainType();
    ((TextView)findViewById(R.id.summary)).setText(summary);
    
    mTypes = intent.getIntArrayExtra(EXTRA_DETAIL_TYPES);
    mValues = intent.getDoubleArrayExtra(EXTRA_DETAIL_VALUES);

    mTitleView = (TextView) findViewById(R.id.name);
    mTitleView.setText(mTitle);
    ((TextView)findViewById(R.id.battery_percentage))
        .setText(String.format("%d%%", percentage));

    mTwoButtonsPanel = (ViewGroup) findViewById(R.id.two_buttons_panel);
    mForceStopButton = (Button) findViewById(R.id.left_button);
    mReportButton = (Button) findViewById(R.id.right_button);
    mForceStopButton.setEnabled(false);
    
    ImageView gaugeImage = (ImageView) findViewById(R.id.gauge);
    mGauge = new PercentageBar();
    mGauge.percent = gaugeValue;
    mGauge.bar = getResources().getDrawable(R.drawable.app_gauge);
    gaugeImage.setImageDrawable(mGauge);

    ImageView iconImage = (ImageView) findViewById(R.id.icon);
    iconImage.setImageDrawable(mAppIcon);

    mDetailsParent = (ViewGroup) findViewById(R.id.details);
    mControlsParent = (ViewGroup) findViewById(R.id.controls);

    fillDetailsSection();
    fillPackagesSection(mUid);
    fillControlsSection(mUid);
    
    if (mUid >= Process.FIRST_APPLICATION_UID) {
        mForceStopButton.setText(R.string.force_stop);
        mForceStopButton.setTag(ACTION_FORCE_STOP);
        mForceStopButton.setOnClickListener(this);
        mReportButton.setText(com.android.internal.R.string.report);
        mReportButton.setTag(ACTION_REPORT);
        mReportButton.setOnClickListener(this);
        
        // check if error reporting is enabled in secure settings
        int enabled = Settings.Secure.getInt(getContentResolver(),
                Settings.Secure.SEND_ACTION_APP_ERROR, 0);
        if (enabled != 0) {
            if (mPackages != null && mPackages.length > 0) {
                try {
                    mApp = getPackageManager().getApplicationInfo(mPackages[0], 0);
                    mInstaller = ApplicationErrorReport.getErrorReportReceiver(
                            this, mPackages[0], mApp.flags);
                } catch (NameNotFoundException e) {
                }
            }
            mReportButton.setEnabled(mInstaller != null);
        } else {
            mTwoButtonsPanel.setVisibility(View.GONE);
        }
    } else {
        mTwoButtonsPanel.setVisibility(View.GONE);
    }
}
 
Example 158
Project: WS171-packages-apps-Browser   File: BrowserBookmarksPage.java View source code 5 votes vote down vote up
private Intent createShortcutIntent(String url, String title,
        Bitmap favicon) {
    final Intent i = new Intent();
    final Intent shortcutIntent = new Intent(Intent.ACTION_VIEW,
            Uri.parse(url));
    long urlHash = url.hashCode();
    long uniqueId = (urlHash << 32) | shortcutIntent.hashCode();
    shortcutIntent.putExtra(Browser.EXTRA_APPLICATION_ID,
            Long.toString(uniqueId));
    i.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    i.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
    if (favicon == null) {
        i.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(
                        BrowserBookmarksPage.this,
                        R.drawable.ic_launcher_shortcut_browser_bookmark));
    } else {
        Bitmap icon = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher_shortcut_browser_bookmark);

        // Make a copy of the regular icon so we can modify the pixels.
        Bitmap copy = icon.copy(Bitmap.Config.ARGB_8888, true);
        Canvas canvas = new Canvas(copy);

        // Make a Paint for the white background rectangle and for
        // filtering the favicon.
        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG
                | Paint.FILTER_BITMAP_FLAG);
        p.setStyle(Paint.Style.FILL_AND_STROKE);
        p.setColor(Color.WHITE);

        // Create a rectangle that is slightly wider than the favicon
        final float iconSize = 16; // 16x16 favicon
        final float padding = 2;   // white padding around icon
        final float rectSize = iconSize + 2 * padding;
        final float y = icon.getHeight() - rectSize;
        RectF r = new RectF(0, y, rectSize, y + rectSize);

        // Draw a white rounded rectangle behind the favicon
        canvas.drawRoundRect(r, 2, 2, p);

        // Draw the favicon in the same rectangle as the rounded rectangle
        // but inset by the padding (results in a 16x16 favicon).
        r.inset(padding, padding);
        canvas.drawBitmap(favicon, null, r, p);
        i.putExtra(Intent.EXTRA_SHORTCUT_ICON, copy);
    }
    // Do not allow duplicate items
    i.putExtra("duplicate", false);
    return i;
}
 
Example 159
Project: property-db   File: InputMethodManagerService.java View source code 5 votes vote down vote up
void setInputMethodLocked(String id, int subtypeId) {
    InputMethodInfo info = mMethodMap.get(id);
    if (info == null) {
        throw new IllegalArgumentException("Unknown id: " + id);
    }

    // See if we need to notify a subtype change within the same IME.
    if (id.equals(mCurMethodId)) {
        final int subtypeCount = info.getSubtypeCount();
        if (subtypeCount <= 0) {
            return;
        }
        final InputMethodSubtype oldSubtype = mCurrentSubtype;
        final InputMethodSubtype newSubtype;
        if (subtypeId >= 0 && subtypeId < subtypeCount) {
            newSubtype = info.getSubtypeAt(subtypeId);
        } else {
            // If subtype is null, try to find the most applicable one from
            // getCurrentInputMethodSubtype.
            newSubtype = getCurrentInputMethodSubtypeLocked();
        }
        if (newSubtype == null || oldSubtype == null) {
            Slog.w(TAG, "Illegal subtype state: old subtype = " + oldSubtype
                    + ", new subtype = " + newSubtype);
            return;
        }
        if (newSubtype != oldSubtype) {
            setSelectedInputMethodAndSubtypeLocked(info, subtypeId, true);
            if (mCurMethod != null) {
                try {
                    refreshImeWindowVisibilityLocked();
                    mCurMethod.changeInputMethodSubtype(newSubtype);
                } catch (RemoteException e) {
                    Slog.w(TAG, "Failed to call changeInputMethodSubtype");
                }
            }
        }
        return;
    }

    // Changing to a different IME.
    final long ident = Binder.clearCallingIdentity();
    try {
        // Set a subtype to this input method.
        // subtypeId the name of a subtype which will be set.
        setSelectedInputMethodAndSubtypeLocked(info, subtypeId, false);
        // mCurMethodId should be updated after setSelectedInputMethodAndSubtypeLocked()
        // because mCurMethodId is stored as a history in
        // setSelectedInputMethodAndSubtypeLocked().
        mCurMethodId = id;

        if (ActivityManagerNative.isSystemReady()) {
            Intent intent = new Intent(Intent.ACTION_INPUT_METHOD_CHANGED);
            intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
            intent.putExtra("input_method_id", id);
            mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT);
        }
        unbindCurrentClientLocked();
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
}
 
Example 160
Project: property-db   File: IntentResolverOld.java View source code 5 votes vote down vote up
private void buildResolveList(Intent intent, FastImmutableArraySet<String> categories,
        boolean debug, boolean defaultOnly,
        String resolvedType, String scheme, List<F> src, List<R> dest, int userId) {
    final String action = intent.getAction();
    final Uri data = intent.getData();
    final String packageName = intent.getPackage();

    final boolean excludingStopped = intent.isExcludingStopped();

    final int N = src != null ? src.size() : 0;
    boolean hasNonDefaults = false;
    int i;
    for (i=0; i<N; i++) {
        F filter = src.get(i);
        int match;
        if (debug) Slog.v(TAG, "Matching against filter " + filter);

        if (excludingStopped && isFilterStopped(filter, userId)) {
            if (debug) {
                Slog.v(TAG, "  Filter's target is stopped; skipping");
            }
            continue;
        }

        // Is delivery being limited to filters owned by a particular package?
        if (packageName != null && !packageName.equals(packageForFilter(filter))) {
            if (debug) {
                Slog.v(TAG, "  Filter is not from package " + packageName + "; skipping");
            }
            continue;
        }

        // Do we already have this one?
        if (!allowFilterResult(filter, dest)) {
            if (debug) {
                Slog.v(TAG, "  Filter's target already added");
            }
            continue;
        }

        match = filter.match(action, resolvedType, scheme, data, categories, TAG);
        if (match >= 0) {
            if (debug) Slog.v(TAG, "  Filter matched!  match=0x" +
                    Integer.toHexString(match));
            if (!defaultOnly || filter.hasCategory(Intent.CATEGORY_DEFAULT)) {
                final R oneResult = newResult(filter, match, userId);
                if (oneResult != null) {
                    dest.add(oneResult);
                }
            } else {
                hasNonDefaults = true;
            }
        } else {
            if (debug) {
                String reason;
                switch (match) {
                    case IntentFilter.NO_MATCH_ACTION: reason = "action"; break;
                    case IntentFilter.NO_MATCH_CATEGORY: reason = "category"; break;
                    case IntentFilter.NO_MATCH_DATA: reason = "data"; break;
                    case IntentFilter.NO_MATCH_TYPE: reason = "type"; break;
                    default: reason = "unknown reason"; break;
                }
                Slog.v(TAG, "  Filter did not match: " + reason);
            }
        }
    }

    if (dest.size() == 0 && hasNonDefaults) {
        Slog.w(TAG, "resolveIntent failed: found match, but none with Intent.CATEGORY_DEFAULT");
    }
}