Java Code Examples for android.content.Context

The following are top voted examples for showing how to use android.content.Context. 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: smsreader-dileepindia-cordova-plugin   File: SMSPlugin.java View source code 13 votes vote down vote up
protected void createIncomingSMSReceiver() {
   Context ctx = this.cordova.getActivity();
 
   this.mReceiver = new BroadcastReceiver()
  {
     public void onReceive(Context context, Intent intent) {
       String action = intent.getAction();
       Log.d("SMSPlugin", "onRecieve: " + action);
       
       if ("android.provider.Telephony.SMS_RECEIVED".equals(action))
       {
         if (SMSPlugin.this.mIntercept) { abortBroadcast();
         }
         Bundle bundle = intent.getExtras();
         if (bundle != null)
         {
           Object[] pdus = (Object[])bundle.get("pdus");
           if (pdus.length != 0)
           {
             for (int i = 0; i < pdus.length; i++) {
               SmsMessage sms = SmsMessage.createFromPdu((byte[])pdus[i]);
               
               JSONObject json = SMSPlugin.this.getJsonFromSmsMessage(sms);
               SMSPlugin.this.onSMSArrive(json);
             }
             
           }
        }
      }
    }
  };
   String[] filterstr = { "android.provider.Telephony.SMS_RECEIVED" };
   for (int i = 0; i < filterstr.length; i++) {
    IntentFilter filter = new IntentFilter(filterstr[i]);
    filter.setPriority(100);
     ctx.registerReceiver(this.mReceiver, filter);
     Log.d("SMSPlugin", "broadcast receiver registered for: " + filterstr[i]);
  }
}
 
Example 2
Project: dlna   File: YouUtility.java View source code 9 votes vote down vote up
public static String ConfigureGetIniPath(Context context){
	if(context != null)
	{
		File file = context.getFilesDir();
		return file.getAbsolutePath();
	}
	else
	{
		return "/data/data/com.youplayer.player/files";
	}
}
 
Example 3
Project: android-stackblur   File: MainActivity.java View source code 8 votes vote down vote up
private Bitmap getBitmapFromAsset(Context context, String strName) {
    AssetManager assetManager = context.getAssets();
    InputStream istr;
    Bitmap bitmap = null;
    try {
        istr = assetManager.open(strName);
        bitmap = BitmapFactory.decodeStream(istr);
    } catch (IOException e) {
        return null;
    }
    return bitmap;
}
 
Example 4
Project: my-ministry-assistant   File: FileUtils.java View source code 8 votes vote down vote up
@TargetApi(Build.VERSION_CODES.FROYO)
public static File getExternalDBFile(Context context, String fileName) {
	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
		return new File(context.getExternalFilesDir(null), fileName);
	}
	else {
		File[] extDBPath = ContextCompat.getExternalFilesDirs(context, null);
		if(extDBPath != null) {
			if(!extDBPath[0].exists()) {
				extDBPath[0].mkdirs();
			}
			return new File(extDBPath[0], fileName);
		}
	}
	return null;
}
 
Example 5
Project: hacktoolkit-android_lib   File: FileUtils.java View source code 8 votes vote down vote up
public static ArrayList<String> readLines(Activity activity, String filename) throws IOException {
	Context context = activity.getApplicationContext();
	ArrayList<String> lines = new ArrayList<String>();
	try {
		FileInputStream fin = context.openFileInput(filename);
		if (fin != null) {
			InputStreamReader inputStreamReader = new InputStreamReader(fin);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String line;
			while (( line = bufferedReader.readLine() ) != null) {
				lines.add(line);
			}
			fin.close();
		}
	} catch (FileNotFoundException fnfe) {
		fnfe.printStackTrace();
	}
	return lines;
}
 
Example 6
Project: dlna   File: YouPlayerAbsoluteLayout.java View source code 7 votes vote down vote up
public LayoutParams(Context c, AttributeSet attrs) {
    super(c, attrs);
    TypedArray a = c.obtainStyledAttributes(attrs,
            R.styleable.AbsoluteLayout_Layout);
    x = a.getDimensionPixelOffset(
            R.styleable.AbsoluteLayout_Layout_layout_x, 0);
    y = a.getDimensionPixelOffset(
            R.styleable.AbsoluteLayout_Layout_layout_y, 0);
    fadingEdgeLength = a.getDimensionPixelOffset(R.styleable.AbsoluteLayout_Layout_fadingEdgeLength, 0);
    toLeftOf = a.getResourceId(R.styleable.AbsoluteLayout_Layout_layout_toLeftOf, 0);
    toRightOf = a.getResourceId(R.styleable.AbsoluteLayout_Layout_layout_toRightOf, 0);
    a.recycle();
}
 
Example 7
Project: hacktoolkit-android_lib   File: FileUtils.java View source code 7 votes vote down vote up
public static int writeLines(Activity activity, String filename, ArrayList<String> lines) throws IOException {
	int linesWritten = 0;
	Context context = activity.getApplicationContext();
	try {
		FileOutputStream fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
		for (String line : lines) {
			// add terminal character so that it doesn't get written as one line
			fos.write((line + "\n").getBytes());
			++linesWritten;
		}
		fos.close();
	} catch (FileNotFoundException fnfe) {
		fnfe.printStackTrace();
	}
	return linesWritten;
}
 
Example 8
Project: DistSysProject   File: SnapshotCache.java View source code 7 votes vote down vote up
public static void storeSnapshot(List<WifiReading> readings, String fileName, Context c) {

		String state = Environment.getExternalStorageState();

		if (Environment.MEDIA_MOUNTED.equals(state)) {
			// We can read and write the external storage
			try {
				JSONArray json = readingsToJson(readings);
				File root = c.getExternalCacheDir();
				File jsonFile = new File(root, constructFileName(fileName));
				FileOutputStream out;
				out = new FileOutputStream(jsonFile);
				out.write(json.toString().getBytes());
				out.close();
				U.showToast(constructFileName(fileName));
				Log.d(TAG, "Successfully stored snapshot to SDCard");
			} catch (Exception e) {
				U.showToast("Could not save the snapshot on the SDCard.");
				Log.e(TAG, "Could not save the snapshot on the SDCard.", e);
			}
		} else {
			U.showToast("Cannot write to external storage.");
		}
	}
 
Example 9
Project: open-bixi-gpstracker   File: CustomUpload.java View source code 7 votes vote down vote up
private void notifyError(Context context, Exception e)
{      
   Log.e( TAG, "Custom upload failed", e);
   String ns = Context.NOTIFICATION_SERVICE;
   NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
   
   int icon = R.drawable.ic_maps_indicator_current_position;
   CharSequence tickerText = context.getText(R.string.customupload_failed);
   long when = System.currentTimeMillis();
   Notification notification = new Notification(icon, tickerText, when);
   
   Context appContext = context.getApplicationContext();
   CharSequence contentTitle = tickerText;
   CharSequence contentText = e.getMessage();
   Intent notificationIntent = new Intent(context, CustomUpload.class);
   PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
   notification.setLatestEventInfo(appContext, contentTitle, contentText, contentIntent);
   notification.flags = Notification.FLAG_AUTO_CANCEL;

   mNotificationManager.notify(NOTIFICATION_ID, notification);
}
 
Example 10
Project: tabulae   File: Satellite.java View source code 7 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static String test(Context context) {
	int a = 0;
	int b = 0;
	int c = 0;
	//if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
	if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M
			|| context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
			&& context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
		for (TheDictionary o : new Satellite(((LocationManager) context.getSystemService(Context.LOCATION_SERVICE)).getLastKnownLocation(LocationManager.GPS_PROVIDER))) {
			a++;
			if (DEBUG) Log.d(TAG, "got: " + o);
		}
	}
	return "counts: " + a + '/' + b + '/' + c;
}
 
Example 11
Project: my-ministry-assistant   File: HouseholderRecentActivityAdapter.java View source code 6 votes vote down vote up
@Override
   public View newView(Context context, Cursor cur, ViewGroup parent) {
	LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       View view = li.inflate(LAYOUT_ID, parent, false);
	ViewHolder holder = new ViewHolder();
	holder.activity_title = (TextView) view.findViewById(R.id.activity_title);
	holder.activity_publications = (LinearLayout) view.findViewById(R.id.activity_publications);
	holder.activity_notes_layout = (LinearLayout) view.findViewById(R.id.activity_notes_layout);
	holder.activity_notes = (TextView) view.findViewById(R.id.activity_notes);
	holder.activity_date = (TextView) view.findViewById(R.id.activity_date);
	view.setTag(holder);
	return view;
}
 
Example 12
Project: dlna   File: YouUtility.java View source code 6 votes vote down vote up
public static void setRecommendRightFlag(Context context, boolean flag) {
	if (context != null) {
		SharedPreferences settings = context.getSharedPreferences(
				RECOMMEND_RIGHT, 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean(RECOMMEND_FIRST, flag);
		editor.commit();
	}
}
 
Example 13
Project: dlna   File: SwitchButton.java View source code 6 votes vote down vote up
private void initView(Context context) {
	mPaint = new Paint();
	mPaint.setColor(Color.WHITE);
	Resources resources = context.getResources();

	// get viewConfiguration
	mClickTimeout = ViewConfiguration.getPressedStateDuration()+ ViewConfiguration.getTapTimeout();
	mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

	// get Bitmap
	bottom = BitmapFactory.decodeResource(resources, R.drawable.switch_button_switch);
	btn_pressed = BitmapFactory.decodeResource(resources,R.drawable.switch_button);
	btn_unpressed = BitmapFactory.decodeResource(resources,R.drawable.switch_button);
	frame = BitmapFactory.decodeResource(resources, R.drawable.switch_button_frame);
	mask = BitmapFactory.decodeResource(resources, R.drawable.switch_button_mask);
	btn = btn_unpressed;

	btnWidth = btn_pressed.getWidth();
	maskWidth = mask.getWidth();
	maskHeight = mask.getHeight();

	btnOffPos = btnWidth / 2;
	btnOnPos = maskWidth - btnWidth / 2;

	btnPos = mChecked ? btnOnPos : btnOffPos;
	realPos = getRealPos(btnPos);
}
 
Example 14
Project: BLEConnect   File: UploadFile.java View source code 6 votes vote down vote up
public UploadFile(Context context, DropboxAPI<?> api, String dropboxPath,
        File file) {
    // We set the context this way so we don't accidentally leak activities
    mContext = context.getApplicationContext();

    mFileLen = file.length();
    mApi = api;
    mPath = dropboxPath;
    mFile = file;

    mDialog = new ProgressDialog(context);
    mDialog.setMax(100);
    mDialog.setMessage("Uploading " + file.getName());
    mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    mDialog.setProgress(0);
    mDialog.setButton("Cancel", new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // This will cancel the putFile operation
            mRequest.abort();
        }
    });
    mDialog.show();
}
 
Example 15
Project: dlna   File: YouUtility.java View source code 6 votes vote down vote up
public static String getClearDefaultFlag(Context context) {
	SharedPreferences sp = context.getSharedPreferences("you_notification", Activity.MODE_PRIVATE);
	String flag = sp.getString(CLEAR_AUTO_FLAG, "");
	if (flag == null || flag.length() == 0) {
		sp.edit().putString(CLEAR_AUTO_FLAG, context.getString(R.string.notification_clear_default_switch))
				.commit();
		flag = context.getString(R.string.notification_clear_default_switch);
	}
	return flag;
}
 
Example 16
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 17
Project: BioWiki   File: ImageHelper.java View source code 6 votes vote down vote up
/**
 * Resizes an image to be placed in the Post Content Editor
 *
 * @param ctx
 * @param filePath
 * @return resized bitmap
 */
public Bitmap getThumbnailForWPImageSpan(Context ctx, String filePath) {
    if (filePath == null)
        return null;

    Display display = ((Activity) ctx).getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int height = display.getHeight();
    if (width > height)
        width = height;

    Uri curUri;

    if (!filePath.contains("content://"))
        curUri = Uri.parse("content://media" + filePath);
    else
        curUri = Uri.parse(filePath);

    if (filePath.contains("video")) {
        int videoId = 0;
        try {
            videoId = Integer.parseInt(curUri.getLastPathSegment());
        } catch (NumberFormatException e) {
        }
        ContentResolver crThumb = ctx.getContentResolver();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        return MediaStore.Video.Thumbnails.getThumbnail(crThumb, videoId, MediaStore.Video.Thumbnails.MINI_KIND,
                options);
    } else {
        int[] dimensions = getImageSize(curUri, ctx);
        float conversionFactor = 0.40f;
        if (dimensions[0] > dimensions[1]) //width > height
            conversionFactor = 0.60f;
        int resizedWidth = (int) (width * conversionFactor);

        // create resized picture
        int rotation = getImageOrientation(ctx, filePath);
        byte[] bytes = createThumbnailFromUri(ctx, curUri, resizedWidth, null, rotation);

        // upload resized picture
        if (bytes != null && bytes.length > 0) {
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        } else {
            return null;
        }
    }
}
 
Example 18
Project: android_Findex   File: ActionReceiver.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if ((intent.getAction() != null)) {
        if (intent.getAction().equals(C.ACTION_REFRESH) ||
                intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            if (!isMyServiceRunning(context)) {
                context.startService(new Intent(context, IndexService.class));
            }
        }
    }
}
 
Example 19
Project: phonegap-geolocation   File: DirectoryManager.java View source code 6 votes vote down vote up
/**
 * Determine if we can use the SD Card to store the temporary file.  If not then use
 * the internal cache directory.
 *
 * @return the absolute path of where to store the file
 */
public static String getTempDirectoryPath(Context ctx) {
    File cache = null;

    // SD Card Mounted
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        cache = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +
                "/Android/data/" + ctx.getPackageName() + "/cache/");
    }
    // Use internal storage
    else {
        cache = ctx.getCacheDir();
    }

    // Create the cache directory if it doesn't exist
    if (!cache.exists()) {
        cache.mkdirs();
    }

    return cache.getAbsolutePath();
}
 
Example 20
Project: dlna   File: YouUtility.java View source code 6 votes vote down vote up
public static int getPackageVersionNum(Context context) {
	PackageManager pm = context.getPackageManager();
	PackageInfo pi = null;
	int versionNum = 0;
	try {
		pi = pm.getPackageInfo(context.getPackageName(), 0);
		versionNum = pi.versionCode;
	} catch (NameNotFoundException e) {
		e.printStackTrace();
	}
	return versionNum;
}
 
Example 21
Project: dlna   File: PlayBorcastFactory.java View source code 6 votes vote down vote up
public static void sendPlayState(Context context, int playState, int playIndex, Item item){
	Intent intent = new Intent(BROCAST_NAME);
	intent.putExtra(PLAY_MUSIC_STATE, playState);
	intent.putExtra(PLAY_MUSIC_INDEX, playIndex);
	ItemFactory.putItemToIntent(item, intent);
	context.sendBroadcast(intent);
}
 
Example 22
Project: Android_Blog_Demos   File: ViewServer.java View source code 6 votes vote down vote up
/**
 * Returns a unique instance of the ViewServer. This method should only be
 * called from the main thread of your application. The server will have
 * the same lifetime as your process.
 * 
 * If your application does not have the <code>android:debuggable</code>
 * flag set in its manifest, the server returned by this method will
 * be a dummy object that does not do anything. This allows you to use
 * the same code in debug and release versions of your application.
 * 
 * @param context A Context used to check whether the application is
 *                debuggable, this can be the application context
 */
public static ViewServer get(Context context) {
    ApplicationInfo info = context.getApplicationInfo();
    if (BUILD_TYPE_USER.equals(Build.TYPE) &&
            (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
        if (sServer == null) {
            sServer = new ViewServer(ViewServer.VIEW_SERVER_DEFAULT_PORT);
        }

        if (!sServer.isRunning()) {
            try {
                sServer.start();
            } catch (IOException e) {
                Log.d(LOG_TAG, "Error:", e);
            }
        }
    } else {
        sServer = new NoopViewServer();
    }

    return sServer;
}
 
Example 23
Project: android_maskable_layout   File: MaskableFrameLayout.java View source code 6 votes vote down vote up
private void construct(Context context, AttributeSet attrs) {
    mHandler = new Handler();
    setDrawingCacheEnabled(true);
    if (Build.VERSION.SDK_INT >= 11) {
        setLayerType(LAYER_TYPE_SOFTWARE, null); //Only works for software layers
    }
    mPaint = createPaint();
    Resources.Theme theme = context.getTheme();
    if (theme != null) {
        TypedArray a = theme.obtainStyledAttributes(
                attrs,
                R.styleable.MaskableLayout,
                0, 0);
        try {
            //Load the mask if specified in xml
            initMask(loadMask(a));
            //Load the mode if specified in xml
            mPorterDuffXferMode = getModeFromInteger(
                    a.getInteger(R.styleable.MaskableLayout_porterduffxfermode, 0));

            initMask(mDrawableMask);
        } finally {
            if (a != null) {
                a.recycle();
            }
        }
    } else {
        log("Couldn't load theme, mask in xml won't be loaded.");
    }
    registerMeasure();
}
 
Example 24
Project: SensorsWebLogger   File: HandleSensors.java View source code 6 votes vote down vote up
public void StopServiceHandlers (Context context) {
    for( Class<?> sensorSingle: sensorClasses ) {
        AlarmManager scheduler = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context.getApplicationContext(), sensorSingle);
        PendingIntent scheduledIntent = PendingIntent.getService(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        scheduler.cancel(scheduledIntent);
        context.stopService(intent);
    }
}
 
Example 25
Project: android_packages_apps_AeroControl   File: Utils.java View source code 6 votes vote down vote up
public static boolean isOnline(Context context) {
    int res = context.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE);
    if (res == PackageManager.PERMISSION_GRANTED) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }

    return true;
}
 
Example 26
Project: dlna   File: YouPhonePowerUtil.java View source code 6 votes vote down vote up
public void unregisterPeceiver(Context context) {
	try{
		if (null != context && null != mBatteryInfoReceiver){
			context.unregisterReceiver(mBatteryInfoReceiver);
			mBatteryInfoReceiver = null;
		}
	}
	catch(Exception e){
		e.printStackTrace();
	}
}
 
Example 27
Project: acacia   File: ServiceProxy.java View source code 6 votes vote down vote up
public ServiceProxy(Context aContext, Class<?> aServiceInterface)
{
    this.pendingInvocations = new LinkedList<>();
    this.context = aContext;
    this.isServiceStopped = false;

    Service serviceAnnotation = aServiceInterface.getAnnotation(Service.class);
    this.useWorkerThread = serviceAnnotation.useWorkerThread();
    this.userImplClass = serviceAnnotation.value();
    Class<? extends AcaciaService> androidService = serviceAnnotation.androidService();

    // Start Android service
    Intent intent = new Intent(aContext, androidService);
    aContext.startService(intent);
    aContext.bindService(intent, this, Context.BIND_AUTO_CREATE);
}
 
Example 28
Project: xface-android   File: XSystemEventCenter.java View source code 6 votes vote down vote up
public XSystemEventCenter(Context context) {
    mContext = context;
    mEvtReceiverRecords = new ArrayList<XSystemEventCenter.EventReceiverRecord>();
    mReceivers = new ConcurrentHashMap<Integer, ArrayList<XISystemEventReceiver>>();
    mHandler = new Handler(context.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MSG_EXEC_PENDING_EVENT:
                notifyPendingEvent();
                break;
            default:
                super.handleMessage(msg);
            }
        }

    };
}
 
Example 29
Project: anewjkuapp   File: KusssDatabaseHelper.java View source code 6 votes vote down vote up
public static void drop(Context context) {
    try {
        context.deleteDatabase(DATABASE_NAME);
    } catch (Exception e) {
        Analytics.sendException(context, e, true);
    }
}
 
Example 30
Project: afwall   File: Api.java View source code 6 votes vote down vote up
private static boolean installBinary(Context ctx, int resId, String filename) {
	try {
		File f = new File(ctx.getDir("bin", 0), filename);
		if (f.exists()) {
			f.delete();
		}
		copyRawFile(ctx, resId, f, "0755");
		return true;
	} catch (Exception e) {
		Log.e(TAG, "installBinary failed: " + e.getLocalizedMessage());
		return false;
	}
}
 
Example 31
Project: my-ministry-assistant   File: Helper.java View source code 6 votes vote down vote up
public static boolean renameDB(Context context) {
	/** Create the file */
	File oldDB = context.getDatabasePath(MinistryDatabase.DATABASE_NAME_OLD);
	/** If the file exists we want to rename it to our new DB name :) */
	if(oldDB.exists())
		oldDB.renameTo(context.getDatabasePath(MinistryDatabase.DATABASE_NAME));
	
	return true;
}
 
Example 32
Project: android-opencv-template   File: AsyncServiceHelper.java View source code 6 votes vote down vote up
public static boolean initOpenCV(String Version, final Context AppContext,
        final LoaderCallbackInterface Callback)
{
    AsyncServiceHelper helper = new AsyncServiceHelper(Version, AppContext, Callback);
    if (AppContext.bindService(new Intent("org.opencv.engine.BIND"),
            helper.mServiceConnection, Context.BIND_AUTO_CREATE))
    {
        return true;
    }
    else
    {
        AppContext.unbindService(helper.mServiceConnection);
        InstallService(AppContext, Callback);
        return false;
    }
}
 
Example 33
Project: BioWiki   File: ApiHelper.java View source code 6 votes vote down vote up
private File getTempFile(Context context) {
    String tempFileName = "wp-" + System.currentTimeMillis();
    try {
        context.openFileOutput(tempFileName, Context.MODE_PRIVATE);
    } catch (FileNotFoundException e) {
        return null;
    }
    return context.getFileStreamPath(tempFileName);
}
 
Example 34
Project: tuberun_android   File: Store.java View source code 6 votes vote down vote up
public  void storeToFile(Context context) {

		FileOutputStream fos;
		try {
			context.deleteFile(FILENAME);
			fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
			ObjectOutputStream oo = new ObjectOutputStream(fos);
			for (T f : list) {
				oo.writeObject(f);
			}
			oo.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
 
Example 35
Project: BioWiki   File: SystemServiceFactoryTest.java View source code 6 votes vote down vote up
public Object get(Context context, String name) {
    System.setProperty("dexmaker.dexcache", context.getCacheDir().getPath());
    if (Context.NOTIFICATION_SERVICE.equals(name)) {
        NotificationManager notificationManager = mock(NotificationManager.class);
        if (sNotificationCallback != null) {
            doAnswer(sNotificationCallback).when(notificationManager).notify(anyInt(), any(Notification.class));
            doAnswer(sNotificationCallback).when(notificationManager).cancel(anyInt());
        }
        return notificationManager;
    } else {
        AppLog.e(T.TESTS, "SystemService:" + name + "No supported in SystemServiceFactoryTest");
    }
    return null;
}
 
Example 36
Project: devcoin-android   File: MenuInflater.java View source code 6 votes vote down vote up
public InflatedOnMenuItemClickListener(Context context, String methodName) {
    mContext = context;
    Class<?> c = context.getClass();
    try {
        mMethod = c.getMethod(methodName, PARAM_TYPES);
    } catch (Exception e) {
        InflateException ex = new InflateException(
                "Couldn't resolve menu item onClick handler " + methodName +
                " in class " + c.getName());
        ex.initCause(e);
        throw ex;
    }
}
 
Example 37
Project: CSipSimple-old   File: RewriterPlugin.java View source code 6 votes vote down vote up
/**
 * Rewrite a number using a given plugin.
 * Warning this should never be done on main thread otherwise will always fail due to thread issues.
 * 
 * @param context The application context to use to talk to plugin
 * @param componentName The fully qualified component name of the plugin
 * @param number The number to rewrite
 */
public static String rewriteNumber(Context context, final String componentName, String number) {
    ComponentName cn = ComponentName.unflattenFromString(componentName);

    Intent it = new Intent(SipManager.ACTION_REWRITE_NUMBER);
    it.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
    it.setComponent(cn);
    
    OnRewriteReceiver resultTreater = new OnRewriteReceiver(number);
    context.sendOrderedBroadcast(it, permission.PROCESS_OUTGOING_CALLS, resultTreater, null,
            Activity.RESULT_OK, null, null);
    
    return resultTreater.getResult();
}
 
Example 38
Project: TravelsApp   File: MonoPackageManager.java View source code 6 votes vote down vote up
public static void LoadApplication (Context context, String runtimeDataDir, String[] apks)
{
	synchronized (lock) {
		if (!initialized) {
			System.loadLibrary("monodroid");
			Locale locale       = Locale.getDefault ();
			String language     = locale.getLanguage () + "-" + locale.getCountry ();
			String filesDir     = context.getFilesDir ().getAbsolutePath ();
			String cacheDir     = context.getCacheDir ().getAbsolutePath ();
			String dataDir      = context.getApplicationInfo ().dataDir + "/lib";
			ClassLoader loader  = context.getClassLoader ();

			Runtime.init (
					language,
					apks,
					runtimeDataDir,
					new String[]{
						filesDir,
						cacheDir,
						dataDir,
					},
					loader,
					new java.io.File (
						android.os.Environment.getExternalStorageDirectory (),
						"Android/data/" + context.getPackageName () + "/files/.__override__").getAbsolutePath (),
					MonoPackageManager_Resources.Assemblies,
					context.getPackageName ());
			initialized = true;
		}
	}
}
 
Example 39
Project: nptornews   File: NewsStoryActivity.java View source code 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
  Long playlistId = -1L;
  Playable playable = null;
  try {
    Context serviceContext = context.createPackageContext(context.getPackageName(),
        Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
    Bundle bundle = intent.getExtras();
    bundle.setClassLoader(serviceContext.getClassLoader());
    playable = bundle.getParcelable(Playable.PLAYABLE_TYPE);
  } catch (PackageManager.NameNotFoundException e)
  {
    Log.e(LOG_TAG, "Unable to parse playing item information", e);
  }
  if (playable != null) {
    playlistId = playable.getId();
  }
  if (playlistId != -1) {
    PlaylistEntry pe = playlistRepository.getPlaylistItemFromId
        (playlistId);
    if (pe == null) return;
    int len = stories.size();
    for (int i = 0; i < len; i++) {
      View v = workspace.getChildAt(i);
      Button listenNow =
          (Button) v.findViewById(R.id.NewsStoryListenNowButton);
      listenNow.setEnabled(!stories.get(i).getId().equals(pe.storyID));
    }
  }
}
 
Example 40
Project: Orange-Android-Demos   File: NavigationBar.java View source code 6 votes vote down vote up
private void initViews(Context context) {
	try {
		listener = (OnNavigationBarSelectedListener) context;
	} catch (Exception e) {
		throw new ClassCastException(context.toString()
				+ " must implement OnNavigationBarSelectedListener");
	}
	LayoutInflater inflater = (LayoutInflater) context
			.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	inflater.inflate(R.layout.navigation_bar, this, true);
	setOnCheckedChangeListener(new OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			switch (checkedId) {
			case R.id.radio_button_fixture:
				listener.onMatchSelected();
				break;
			case R.id.radio_button_news:
				listener.onNewsSelected();
				break;
			case R.id.radio_button_rank:
				listener.onRankSelected();
				break;
			case R.id.radio_button_profile:
				listener.onProfileSelected();
				break;
			}
		}
	});
}
 
Example 41
Project: MDP-Group-10   File: MainActivity.java View source code 6 votes vote down vote up
public void load(){
	SharedPreferences sp = getSharedPreferences("MyData", Context.MODE_PRIVATE);
	f1 = sp.getString("Function1", DEFAULT);
	f2 = sp.getString("Function2", DEFAULT);
	f1b = sp.getString("Function1b", DEFAULT);
	f2b = sp.getString("Function2b", DEFAULT);
	if(f1.equals(DEFAULT) || f2.equals(DEFAULT)||f1b.equals(DEFAULT) || f2b.equals(DEFAULT)){
		Toast.makeText(this, "No Function Data Found", Toast.LENGTH_SHORT).show();
	}else{
		Toast.makeText(this, "Function Loaded", Toast.LENGTH_SHORT).show();
	}

}
 
Example 42
Project: Blah   File: NotificationReceiver.java View source code 6 votes vote down vote up
public void onReceive(Context context, Intent intent) {

        phone = intent.getStringExtra("phone");

        //??app??????
        if (SystemUtil.isAppAlive(context, "com.v2cc.im.blah")) {
            //????????????MessageActivity????????????app????????
            //?Task????????????Back????????????????????????
            //MessageActivity,??Back??????MainActivity???????
            //MessageActivity??????MainActivity?
            Log.d("NotificationReceiver", "the app process is alive");
            Intent mainIntent = new Intent(context, MainActivity.class);
            //?MainAtivity?launchMode???SingleTask, ?????flag???Intent.FLAG_CLEAR_TOP,
            //??Task???MainActivity???????????????????Activity??????
            //??Task????MainActivity?????????
            mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            Intent mIntent = new Intent(context, MessageActivity.class);
            mIntent.putExtra("phone", phone);
            Intent[] intents = {mainIntent, mIntent};
            context.startActivities(intents);
        } else {
            //??app?????????????app??MessageActivity???????Intent??????
            //SplashActivity??MainActivity???app??????????MainActivity????????
            // ?????MessageActivity???
            Log.d("NotificationReceiver", "the app process is dead");
            Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("com.v2cc.im.blah");
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            Bundle args = new Bundle();
            args.putString("phone", phone);
            launchIntent.putExtra(Constants.EXTRA_BUNDLE, args);
            context.startActivity(launchIntent);
        }
    }
 
Example 43
Project: dlna   File: ShareActivity.java View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	
	setContentView(R.layout.share);
	
	initView();
	initDate();

	startService(new Intent(this,ShareService.class));

	final Intent intent = new Intent(this,ShareService.class);
	getApplicationContext().bindService(intent,serviceConnection,Context.BIND_AUTO_CREATE);
	
}
 
Example 44
Project: property-db   File: SimSmsInterfaceManager.java View source code 6 votes vote down vote up
/**
 * Retrieves all messages currently stored on ICC.
 *
 * @return list of SmsRawData of all sms on ICC
 */
public List<SmsRawData> getAllMessagesFromIccEf() {
    if (DBG) log("getAllMessagesFromEF");

    Context context = mPhone.getContext();

    context.enforceCallingPermission(
            "android.permission.RECEIVE_SMS",
            "Reading messages from SIM");
    synchronized(mLock) {
        Message response = mHandler.obtainMessage(EVENT_LOAD_DONE);
        mPhone.getIccFileHandler().loadEFLinearFixedAll(IccConstants.EF_SMS, response);

        try {
            mLock.wait();
        } catch (InterruptedException e) {
            log("interrupted while trying to load from the SIM");
        }
    }
    return mSms;
}
 
Example 45
Project: BioWiki   File: PostUploadServiceTest.java View source code 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    testContext = getContext().createPackageContext("kr.kdev.dg1s.biowiki.test", Context.CONTEXT_IGNORE_SECURITY);
    targetContext = new RenamingDelegatingContext(getContext(), "test_");

    // Init contexts
    XMLRPCFactoryTest.sContext = getContext();
    RestClientFactoryTest.sContext = getContext();
    AppLog.v(AppLog.T.TESTS, "Contexts set");

    // Set mode to Customizable
    XMLRPCFactoryTest.sMode = XMLRPCFactoryTest.Mode.CUSTOMIZABLE_XML;
    RestClientFactoryTest.sMode = RestClientFactoryTest.Mode.CUSTOMIZABLE;
    AppLog.v(AppLog.T.TESTS, "Modes set to customizable");
}
 
Example 46
Project: Subsonic   File: Util.java View source code 6 votes vote down vote up
public static void applyTheme(Context context, String theme) {
	context.setTheme(getThemeRes(context, theme));

	SharedPreferences prefs = Util.getPreferences(context);
	if(prefs.getBoolean(Constants.PREFERENCES_KEY_OVERRIDE_SYSTEM_LANGUAGE, false)) {
		Configuration config = new Configuration();
		config.locale = Locale.ENGLISH;
		context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
	}
}
 
Example 47
Project: SealBrowser   File: MemoryPressureListener.java View source code 6 votes vote down vote up
@CalledByNative
private static void registerSystemCallback(Context context) {
    context.registerComponentCallbacks(
            new ComponentCallbacks2() {
                @Override
                public void onTrimMemory(int level) {
                    maybeNotifyMemoryPresure(level);
                }

                @Override
                public void onLowMemory() {
                    nativeOnMemoryPressure(MemoryPressureLevelList.MEMORY_PRESSURE_CRITICAL);
                }

                @Override
                public void onConfigurationChanged(Configuration configuration) {
                }
            });
}
 
Example 48
Project: DemoProject   File: RemoteService.java View source code 6 votes vote down vote up
public void onClick(View v) {
    if (mCurConnection != null) {
        unbindService(mCurConnection);
        mCurConnection = null;
    }
    ServiceConnection conn = new MyServiceConnection();
    if (bindService(new Intent(IRemoteService.class.getName()),
            conn, Context.BIND_AUTO_CREATE | Context.BIND_ABOVE_CLIENT)) {
        mCurConnection = conn;
    }
}
 
Example 49
Project: WelikeAndroid   File: WelikeBitmap.java View source code 6 votes vote down vote up
/**
    * ????????
    *
    * @param view            ??????
    * @param url             ???Url
    * @param width           ??
    * @param height          ??
    * @param loadingDrawable ?????????R??
    * @param errorDrawable   ???????R??
    * @param callback        ???????
    * @return ?????????
    */
   @SuppressLint("NewApi") @SuppressWarnings("deprecation")
public BitmapRequest loadBitmap(View view, String url, int width, int height, int loadingDrawable, int errorDrawable, BitmapCallback callback) {
       Context context = WelikeContext.getApplication();
       Drawable loading = null;
       if (loadingDrawable != 0) {
           if (Build.VERSION.SDK_INT > 21) {
               loading = context.getDrawable(loadingDrawable);
           } else {
               loading = context.getResources().getDrawable(loadingDrawable);
           }
       }
       Drawable error = null;
       if (errorDrawable != 0) {
           if (Build.VERSION.SDK_INT > 21) {
               error = context.getDrawable(errorDrawable);
           } else {
               error = context.getResources().getDrawable(errorDrawable);
           }
       }
       return loadBitmap(view, url, width, height, loading, error, callback);
   }
 
Example 50
Project: dlna   File: MusicPlayerActivity.java View source code 6 votes vote down vote up
@SuppressLint("NewApi") public void showplaylist(View parent) {
		if (popWindown == null) {
			LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			popView = layoutInflater.inflate(R.layout.music_play_list, null);
			ListView arraylist = (ListView) popView
					.findViewById(R.id.arraylist);
			arraylist.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					mPlayerEngineImpl.openPlayBeanlist(SoftApplication.getInstance().getMusicPlaylists(), arg2);
//					mItemsList = MediaManager.getInstance().setMusicList(null);
					mPlayerEngineImpl.stop();
					mPlayerEngineImpl.prev();
					mPlayerEngineImpl.next();
					
				}
			});
			// LmPlayerEngineImpl.getPlaylist();
			List<PlaylistBean> lists = SoftApplication.getInstance().getMusicPlaylists();
//			lists.add( new PlaylistBean("title","local","",null));
			MusicPlayListAdapter musicPlayListAdapter = new MusicPlayListAdapter(
					MusicPlayerActivity.this, SoftApplication.getInstance()
							.getMusicPlaylists());
			arraylist.setAdapter(musicPlayListAdapter);
			popWindown = new PopupWindow(popView, 200, 350);
			
			

		}

		popWindown.setFocusable(true);
		popWindown.setOutsideTouchable(true);
		popWindown.setBackgroundDrawable(new BitmapDrawable());
		WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		// ??????:????????-PopupWindow??????
		int xPos = windowManager.getDefaultDisplay().getWidth() / 2;
		Log.i("coder", "xPos:" + xPos);

		popWindown.showAsDropDown(parent, xPos, 0);

	}
 
Example 51
Project: property-db   File: ActivityThread.java View source code 6 votes vote down vote up
public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
        int flags, int userId) {
    synchronized (mPackages) {
        WeakReference<LoadedApk> ref;
        if ((flags&Context.CONTEXT_INCLUDE_CODE) != 0) {
            ref = mPackages.get(packageName);
        } else {
            ref = mResourcePackages.get(packageName);
        }
        LoadedApk packageInfo = ref != null ? ref.get() : null;
        //Slog.i(TAG, "getPackageInfo " + packageName + ": " + packageInfo);
        //if (packageInfo != null) Slog.i(TAG, "isUptoDate " + packageInfo.mResDir
        //        + ": " + packageInfo.mResources.getAssets().isUpToDate());
        if (packageInfo != null && (packageInfo.mResources == null
                || packageInfo.mResources.getAssets().isUpToDate())) {
            if (packageInfo.isSecurityViolation()
                    && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
                throw new SecurityException(
                        "Requesting code from " + packageName
                        + " to be run in process "
                        + mBoundApplication.processName
                        + "/" + mBoundApplication.appInfo.uid);
            }
            return packageInfo;
        }
    }

    ApplicationInfo ai = null;
    try {
        ai = getPackageManager().getApplicationInfo(packageName,
                PackageManager.GET_SHARED_LIBRARY_FILES, userId);
    } catch (RemoteException e) {
        // Ignore
    }

    if (ai != null) {
        return getPackageInfo(ai, compatInfo, flags);
    }

    return null;
}
 
Example 52
Project: XGPM   File: MainActivity.java View source code 6 votes vote down vote up
@SuppressLint("WorldReadableFiles")
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getPreferenceManager().setSharedPreferencesMode(Context.MODE_WORLD_READABLE);
    addPreferencesFromResource(R.xml.preferences);
}
 
Example 53
Project: AmazeFileManager   File: FileUtil.java View source code 6 votes vote down vote up
/**
 * Get a list of external SD card paths. (Kitkat or higher.)
 *
 * @return A list of external SD card paths.
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
private static String[] getExtSdCardPaths(Context context) {
    List<String> paths = new ArrayList<String>();
    for (File file : context.getExternalFilesDirs("external")) {
        if (file != null && !file.equals(context.getExternalFilesDir("external"))) {
            int index = file.getAbsolutePath().lastIndexOf("/Android/data");
            if (index < 0) {
                Log.w("AmazeFileUtils", "Unexpected external file dir: " + file.getAbsolutePath());
            }
            else {
                String path = file.getAbsolutePath().substring(0, index);
                try {
                    path = new File(path).getCanonicalPath();
                }
                catch (IOException e) {
                    // Keep non-canonical path.
                }
                paths.add(path);
            }
        }
    }
    if(paths.isEmpty())paths.add("/storage/sdcard1");
    return paths.toArray(new String[0]);
}
 
Example 54
Project: xface-android   File: XTransferSecurityPolicy.java View source code 6 votes vote down vote up
/**
 * ?apps.pref?????app?md5?
 *
 * @param appId
 * @return
 */
private String readPrefMd5(String appId) {
    SharedPreferences preference = mSysCtx.getContext()
            .getSharedPreferences(
                    XPreInstallAppsTransferPolicy.APPS_MD5_FILE_NAME,
                    Context.MODE_WORLD_READABLE
                            | Context.MODE_WORLD_WRITEABLE);
    String md5 = preference.getString(appId, null);
    if (null == md5) {
        XLog.d(CLASS_NAME, "App id: " + appId + " not found in "
                + XPreInstallAppsTransferPolicy.APPS_MD5_FILE_NAME);
        return null;
    }
    return md5;
}
 
Example 55
Project: WiFi-Automatic   File: Locations.java View source code 6 votes vote down vote up
@Override
protected void onResume() {
    super.onResume();
    SharedPreferences prefs =
            getSharedPreferences(getPackageName() + "_preferences", Context.MODE_MULTI_PROCESS);
    findViewById(R.id.timeoutwarning).setVisibility(prefs.getBoolean("off_no_network", true) &&
            prefs.getInt("no_network_timeout", Receiver.TIMEOUT_NO_NETWORK) < 5 ? View.VISIBLE :
            View.GONE);

    boolean locationAccessEnabled = true;
    try {
        locationAccessEnabled = (Build.VERSION.SDK_INT < 19 && !TextUtils.isEmpty(
                Settings.Secure.getString(getContentResolver(),
                        Settings.Secure.LOCATION_PROVIDERS_ALLOWED))) ||
                (Build.VERSION.SDK_INT >= 19 && Settings.Secure
                        .getInt(getContentResolver(), Settings.Secure.LOCATION_MODE) !=
                        Settings.Secure.LOCATION_MODE_OFF);
    } catch (Exception e) {
        e.printStackTrace();
    }
    findViewById(R.id.locationsettingswarning)
            .setVisibility(locationAccessEnabled ? View.GONE : View.VISIBLE);

    if (PermissionChecker
            .checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) !=
            PermissionChecker.PERMISSION_GRANTED || PermissionChecker
            .checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
            PermissionChecker.PERMISSION_GRANTED) {
        findViewById(R.id.permissionswarning).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                ActivityCompat.requestPermissions(Locations.this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSIONS);
            }
        });
    } else {
        findViewById(R.id.permissionswarning).setVisibility(View.GONE);
    }
}
 
Example 56
Project: Wei.Lib2A   File: FStoreLoc.java View source code 6 votes vote down vote up
/**??App???????????**/
public File getBaseDir(Context context, DirLevel level) throws SdCardNotMountedException, SdCardNotValidException, FileCreateFailureException {
	//ensureCurrent(context);
	checkLevel(level);
	File file = null;
	SdCard sdcardTo = null;
	if (level != DirLevel.PRIVATE && baseDirName != null) sdcardTo = getCustomDirCreatableSdCard(context);
	if (level != DirLevel.CUSTOM && sdcardTo == null) sdcardTo = getValidSdCard(context);
	if (sdcardTo != null) {
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			//?????????????????????
			context.getFilesDir();
			context.getExternalCacheDirs();
		}
		file = FileUtils.makeDir(getAppDirPath(context, sdcardTo, level), true);
	} else {
		if (level == DirLevel.CUSTOM) {
			throw new SdCardNotValidException("???????????");
		}
		/*????????dataDirEnabled=false?anotherCardEnabled?false????????????true???????
		 ????????????*/
		if (sdcardDef == Storage.SDCARD) {	//????????????????????????
			if (!sdcardDef.isMounted(context)) {
				L.i(LOG_TAG, "getBaseDir()--???????");
				throw new SdCardNotMountedException("???????");
			} else if (!sdcardDef.isValid(context)) {
				L.i(LOG_TAG, "getBaseDir()--?????????????");
				throw new SdCardNotValidException("?????????????");
			}
		}
		L.i(LOG_TAG, "getBaseDir()--???????????????????????");
		throw new SdCardNotValidException("???????????????????????");
	}
	return file;
}
 
Example 57
Project: codemap   File: ProjectController.java View source code 6 votes vote down vote up
public static ArrayList<String> getProjectsList(Context context) {
	ArrayList<String> result = new ArrayList<String>();
			
	String[] fileList = context.fileList();
	
	for(String filename: fileList) {
		if(filename.endsWith(".project")) {
			String projectName = filename.substring(0, filename.length()
					- ".project".length());
			result.add(projectName);
		}
	}

	return result;
}
 
Example 58
Project: property-db   File: PackageMonitor.java View source code 6 votes vote down vote up
public void register(Context context, Looper thread, UserHandle user,
        boolean externalStorage) {
    if (mRegisteredContext != null) {
        throw new IllegalStateException("Already registered");
    }
    mRegisteredContext = context;
    if (thread == null) {
        synchronized (sLock) {
            if (sBackgroundThread == null) {
                sBackgroundThread = new HandlerThread("PackageMonitor",
                        android.os.Process.THREAD_PRIORITY_BACKGROUND);
                sBackgroundThread.start();
                sBackgroundHandler = new Handler(sBackgroundThread.getLooper());
            }
            mRegisteredHandler = sBackgroundHandler;
        }
    } else {
        mRegisteredHandler = new Handler(thread);
    }
    if (user != null) {
        context.registerReceiverAsUser(this, user, sPackageFilt, null, mRegisteredHandler);
        context.registerReceiverAsUser(this, user, sNonDataFilt, null, mRegisteredHandler);
        if (externalStorage) {
            context.registerReceiverAsUser(this, user, sExternalFilt, null,
                    mRegisteredHandler);
        }
    } else {
        context.registerReceiver(this, sPackageFilt, null, mRegisteredHandler);
        context.registerReceiver(this, sNonDataFilt, null, mRegisteredHandler);
        if (externalStorage) {
            context.registerReceiver(this, sExternalFilt, null, mRegisteredHandler);
        }
    }
}
 
Example 59
Project: DemoProject   File: RemoteService.java View source code 6 votes vote down vote up
public void onClick(View v) {
    if (mCurConnection != null) {
        unbindService(mCurConnection);
        mCurConnection = null;
    }
    ServiceConnection conn = new MyServiceConnection();
    if (bindService(mBindIntent, conn,
            Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT)) {
        mCurConnection = conn;
    }
}
 
Example 60
Project: SysServiceProxyLib   File: RootPermUtils.java View source code 6 votes vote down vote up
public static String[] getRootJarCommand(Context cxt, String cmd, String... cmdParams) {
    String exportCmd = "export CLASSPATH=" + cxt.getPackageCodePath();
    String rootJarCmd = "/system/bin/app_process /system/bin "
            + SysServiceProxyDaemon.class.getName() + " " + cmd;
    if (cmdParams.length > 0) {
        for (String p : cmdParams) {
            rootJarCmd = rootJarCmd + " " + p;
        }
    }
    return new String[] { exportCmd, rootJarCmd };
}
 
Example 61
Project: sdk-support   File: DocumentsContractApi19.java View source code 6 votes vote down vote up
public static boolean canRead(Context context, Uri self) {
    // Ignore if grant doesn't allow read
    if (context.checkCallingOrSelfUriPermission(self, Intent.FLAG_GRANT_READ_URI_PERMISSION)
            != PackageManager.PERMISSION_GRANTED) {
        return false;
    }

    // Ignore documents without MIME
    if (TextUtils.isEmpty(getRawType(context, self))) {
        return false;
    }

    return true;
}
 
Example 62
Project: SealBrowser   File: AwSettings.java View source code 6 votes vote down vote up
public AwSettings(Context context,
        boolean isAccessFromFileURLsGrantedByDefault,
        boolean supportsLegacyQuirks) {
   boolean hasInternetPermission = context.checkPermission(
                android.Manifest.permission.INTERNET,
                Process.myPid(),
                Process.myUid()) == PackageManager.PERMISSION_GRANTED;
    synchronized (mAwSettingsLock) {
        mHasInternetPermission = hasInternetPermission;
        mBlockNetworkLoads = !hasInternetPermission;
        mEventHandler = new EventHandler();
        if (isAccessFromFileURLsGrantedByDefault) {
            mAllowUniversalAccessFromFileURLs = true;
            mAllowFileAccessFromFileURLs = true;
        }

        mDefaultTextEncoding = AwResource.getDefaultTextEncoding();
        mUserAgent = LazyDefaultUserAgent.sInstance;

        // Best-guess a sensible initial value based on the features supported on the device.
        mSpatialNavigationEnabled = !context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_TOUCHSCREEN);

        // Respect the system setting for password echoing.
        mPasswordEchoEnabled = Settings.System.getInt(context.getContentResolver(),
                Settings.System.TEXT_SHOW_PASSWORD, 1) == 1;

        // By default, scale the text size by the system font scale factor. Embedders
        // may override this by invoking setTextZoom().
        mTextSizePercent *= context.getResources().getConfiguration().fontScale;

        mSupportLegacyQuirks = supportsLegacyQuirks;
    }
    // Defer initializing the native side until a native WebContents instance is set.
}
 
Example 63
Project: Rejsekort-Reminder   File: TrackerService.java View source code 6 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();

	profile = new DefaultProfile();
	handler = new Handler();
	logger = new Logger();

	notificationManager =  (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
	vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

	modeChooserReceiver = new ModeChooserReceiver();
	registerReceiver(modeChooserReceiver, new IntentFilter(FORCE_TRANSPORTATION_MODE));
}
 
Example 64
Project: property-db   File: UsbSettingsManager.java View source code 6 votes vote down vote up
public UsbSettingsManager(Context context, UserHandle user) {
    if (DEBUG) Slog.v(TAG, "Creating settings for " + user);

    try {
        mUserContext = context.createPackageContextAsUser("android", 0, user);
    } catch (NameNotFoundException e) {
        throw new RuntimeException("Missing android package");
    }

    mContext = context;
    mPackageManager = mUserContext.getPackageManager();

    mUser = user;
    mSettingsFile = new AtomicFile(new File(
            Environment.getUserSystemDirectory(user.getIdentifier()),
            "usb_device_manager.xml"));

    synchronized (mLock) {
        if (UserHandle.OWNER.equals(user)) {
            upgradeSingleUserLocked();
        }
        readSettingsLocked();
    }

    mPackageMonitor.register(mUserContext, null, true);
}
 
Example 65
Project: property-db   File: PhoneWindow.java View source code 6 votes vote down vote up
/**
 * Initializes the menu associated with the given panel feature state. You
 * must at the very least set PanelFeatureState.menu to the Menu to be
 * associated with the given panel state. The default implementation creates
 * a new menu for the panel state.
 *
 * @param st The panel whose menu is being initialized.
 * @return Whether the initialization was successful.
 */
protected boolean initializePanelMenu(final PanelFeatureState st) {
    Context context = getContext();

    // If we have an action bar, initialize the menu with a context themed for it.
    if ((st.featureId == FEATURE_OPTIONS_PANEL || st.featureId == FEATURE_ACTION_BAR) &&
            mActionBar != null) {
        TypedValue outValue = new TypedValue();
        Resources.Theme currentTheme = context.getTheme();
        currentTheme.resolveAttribute(com.android.internal.R.attr.actionBarWidgetTheme,
                outValue, true);
        final int targetThemeRes = outValue.resourceId;

        if (targetThemeRes != 0 && context.getThemeResId() != targetThemeRes) {
            context = new ContextThemeWrapper(context, targetThemeRes);
        }
    }

    final MenuBuilder menu = new MenuBuilder(context);

    menu.setCallback(this);
    st.setMenu(menu);

    return true;
}
 
Example 66
Project: FrameCode   File: ProgressDialogUtil.java View source code 6 votes vote down vote up
public static synchronized void showProgressDialog(Context context, String content) {

        if (context instanceof Activity) {


            if (progressDialog == null || !context.equals(progressDialog.getOwnerActivity()) || !progressDialog.isShowing()) {

                dismissProgressDialog();

                if (StringUtils.isEmpty(content)) {

                    content = "???...";
                }
                if (dialogMaker != null) {

                    progressDialog = dialogMaker.makeDialog(context);

                } else {

                    defaultProgressDialogMaker.setContent(content);

                    progressDialog = defaultProgressDialogMaker.makeDialog(context);
                }

                progressDialog.setOwnerActivity((Activity) context);

                progressDialog.show();
            }

            level++;

        }
    }
 
Example 67
Project: DemoProject   File: RemoteService.java View source code 6 votes vote down vote up
public void onClick(View v) {
    if (mCurConnection != null) {
        unbindService(mCurConnection);
        mCurConnection = null;
    }
    ServiceConnection conn = new MyServiceConnection(true);
    if (bindService(mBindIntent, conn,
            Context.BIND_AUTO_CREATE | Context.BIND_WAIVE_PRIORITY)) {
        mCurConnection = conn;
    }
}
 
Example 68
Project: BioWiki   File: BioWikiDB.java View source code 5 votes vote down vote up
public BioWikiDB(Context ctx) {
    this.context = ctx;
    db = ctx.openOrCreateDatabase(DATABASE_NAME, 0, null);

    // Create tables if they don't exist
    db.execSQL(CREATE_TABLE_SETTINGS);
    db.execSQL(CREATE_TABLE_POSTS);
    db.execSQL(CREATE_TABLE_CATEGORIES);
    db.execSQL(CREATE_TABLE_QUICKPRESS_SHORTCUTS);
    db.execSQL(CREATE_TABLE_MEDIA);
    db.execSQL(CREATE_TABLE_THEMES);
    db.execSQL(CREATE_TABLE_NOTES);
    CommentTable.createTables(db);

    // Update tables for new installs and app updates
    int currentVersion = db.getVersion();
    switch (currentVersion) {
        case 0:
            // New install
            currentVersion++;
        case 1:
            // Add columns that were added in very early releases, then move on to version 9
            db.execSQL(ADD_BLOGID);
            db.execSQL(UPDATE_BLOGID);
            db.execSQL(ADD_LOCATION_FLAG);
            db.execSQL(ADD_DOTCOM_USERNAME);
            db.execSQL(ADD_DOTCOM_PASSWORD);
            db.execSQL(ADD_API_KEY);
            db.execSQL(ADD_API_BLOGID);
            db.execSQL(ADD_DOTCOM_FLAG);
            db.execSQL(ADD_WP_VERSION);
            currentVersion = 9;
        case 9:
            db.execSQL(ADD_HTTPUSER);
            db.execSQL(ADD_HTTPPASSWORD);
            migratePasswords();
            currentVersion++;
        case 10:
            db.delete(POSTS_TABLE, null, null);
            db.execSQL(CREATE_TABLE_POSTS);
            db.execSQL(ADD_POST_FORMATS);
            currentVersion++;
        case 11:
            db.execSQL(ADD_SCALED_IMAGE);
            db.execSQL(ADD_SCALED_IMAGE_IMG_WIDTH);
            db.execSQL(ADD_LOCAL_POST_CHANGES);
            currentVersion++;
        case 12:
            db.execSQL(ADD_FEATURED_IN_POST);
            currentVersion++;
        case 13:
            db.execSQL(ADD_HOME_URL);
            currentVersion++;
        case 14:
            db.execSQL(ADD_BLOG_OPTIONS);
            currentVersion++;
        case 15:
            // No longer used (preferences migration)
            currentVersion++;
        case 16:
            //migrateWPComAccount();
            currentVersion++;
        case 17:
            db.execSQL(ADD_PARENTID_IN_CATEGORIES);
            currentVersion++;
        case 18:
            db.execSQL(ADD_ACCOUNTS_ADMIN_FLAG);
            db.execSQL(ADD_MEDIA_FILE_URL);
            db.execSQL(ADD_MEDIA_THUMBNAIL_URL);
            db.execSQL(ADD_MEDIA_UNIQUE_ID);
            db.execSQL(ADD_MEDIA_BLOG_ID);
            db.execSQL(ADD_MEDIA_DATE_GMT);
            db.execSQL(ADD_MEDIA_UPLOAD_STATE);
            currentVersion++;
        case 19:
            // revision 20: create table "notes"
            currentVersion++;
        case 20:
            db.execSQL(ADD_ACCOUNTS_HIDDEN_FLAG);
            currentVersion++;
        case 21:
            db.execSQL(ADD_MEDIA_VIDEOPRESS_SHORTCODE);
            currentVersion++;
            // version 23 added CommentTable.java, version 24 changed the comment table schema
        case 22:
            currentVersion++;
        case 23:
            CommentTable.reset(db);
            currentVersion++;
        case 24:
            currentVersion++;
        case 25:
            //ver 26 "virtually" remove columns 'lastCommentId' and 'runService' from the DB
            //SQLite supports a limited subset of ALTER TABLE. 
            //The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. 
            //It is not possible to rename a column, remove a column, or add or remove constraints from a table.
            currentVersion++;
    }
    db.setVersion(DATABASE_VERSION);
}
 
Example 69
Project: droidel   File: View.java View source code 5 votes vote down vote up
/**
 * Perform inflation from XML and apply a class-specific base style. This
 * constructor of View allows subclasses to use their own base style when
 * they are inflating. For example, a Button class's constructor would call
 * this version of the super class constructor and supply
 * <code>R.attr.buttonStyle</code> for <var>defStyle</var>; this allows
 * the theme's button style to modify all of the base view attributes (in
 * particular its background) as well as the Button class's attributes.
 *
 * @param context The Context the view is running in, through which it can
 *        access the current theme, resources, etc.
 * @param attrs The attributes of the XML tag that is inflating the view.
 * @param defStyleAttr An attribute in the current theme that contains a
 *        reference to a style resource to apply to this view. If 0, no
 *        default style will be applied.
 * @see #View(Context, AttributeSet)
 */
public View(Context context, AttributeSet attrs, int defStyleAttr) {
    this(context);

    TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.View,
            defStyleAttr, 0);

    Drawable background = null;

    int leftPadding = -1;
    int topPadding = -1;
    int rightPadding = -1;
    int bottomPadding = -1;
    int startPadding = UNDEFINED_PADDING;
    int endPadding = UNDEFINED_PADDING;

    int padding = -1;

    int viewFlagValues = 0;
    int viewFlagMasks = 0;

    boolean setScrollContainer = false;

    int x = 0;
    int y = 0;

    float tx = 0;
    float ty = 0;
    float rotation = 0;
    float rotationX = 0;
    float rotationY = 0;
    float sx = 1f;
    float sy = 1f;
    boolean transformSet = false;

    int scrollbarStyle = SCROLLBARS_INSIDE_OVERLAY;
    int overScrollMode = mOverScrollMode;
    boolean initializeScrollbars = false;

    boolean startPaddingDefined = false;
    boolean endPaddingDefined = false;
    boolean leftPaddingDefined = false;
    boolean rightPaddingDefined = false;

    final int targetSdkVersion = context.getApplicationInfo().targetSdkVersion;

    final int N = a.getIndexCount();
    for (int i = 0; i < N; i++) {
        int attr = a.getIndex(i);
        switch (attr) {
            case com.android.internal.R.styleable.View_background:
                background = a.getDrawable(attr);
                break;
            case com.android.internal.R.styleable.View_padding:
                padding = a.getDimensionPixelSize(attr, -1);
                mUserPaddingLeftInitial = padding;
                mUserPaddingRightInitial = padding;
                leftPaddingDefined = true;
                rightPaddingDefined = true;
                break;
             case com.android.internal.R.styleable.View_paddingLeft:
                leftPadding = a.getDimensionPixelSize(attr, -1);
                mUserPaddingLeftInitial = leftPadding;
                leftPaddingDefined = true;
                break;
            case com.android.internal.R.styleable.View_paddingTop:
                topPadding = a.getDimensionPixelSize(attr, -1);
                break;
            case com.android.internal.R.styleable.View_paddingRight:
                rightPadding = a.getDimensionPixelSize(attr, -1);
                mUserPaddingRightInitial = rightPadding;
                rightPaddingDefined = true;
                break;
            case com.android.internal.R.styleable.View_paddingBottom:
                bottomPadding = a.getDimensionPixelSize(attr, -1);
                break;
            case com.android.internal.R.styleable.View_paddingStart:
                startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
                startPaddingDefined = (startPadding != UNDEFINED_PADDING);
                break;
            case com.android.internal.R.styleable.View_paddingEnd:
                endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING);
                endPaddingDefined = (endPadding != UNDEFINED_PADDING);
                break;
            case com.android.internal.R.styleable.View_scrollX:
                x = a.getDimensionPixelOffset(attr, 0);
                break;
            case com.android.internal.R.styleable.View_scrollY:
                y = a.getDimensionPixelOffset(attr, 0);
                break;
            case com.android.internal.R.styleable.View_alpha:
                setAlpha(a.getFloat(attr, 1f));
                break;
            case com.android.internal.R.styleable.View_transformPivotX:
                setPivotX(a.getDimensionPixelOffset(attr, 0));
                break;
            case com.android.internal.R.styleable.View_transformPivotY:
                setPivotY(a.getDimensionPixelOffset(attr, 0));
                break;
            case com.android.internal.R.styleable.View_translationX:
                tx = a.getDimensionPixelOffset(attr, 0);
                transformSet = true;
                break;
            case com.android.internal.R.styleable.View_translationY:
                ty = a.getDimensionPixelOffset(attr, 0);
                transformSet = true;
                break;
            case com.android.internal.R.styleable.View_rotation:
                rotation = a.getFloat(attr, 0);
                transformSet = true;
                break;
            case com.android.internal.R.styleable.View_rotationX:
                rotationX = a.getFloat(attr, 0);
                transformSet = true;
                break;
            case com.android.internal.R.styleable.View_rotationY:
                rotationY = a.getFloat(attr, 0);
                transformSet = true;
                break;
            case com.android.internal.R.styleable.View_scaleX:
                sx = a.getFloat(attr, 1f);
                transformSet = true;
                break;
            case com.android.internal.R.styleable.View_scaleY:
                sy = a.getFloat(attr, 1f);
                transformSet = true;
                break;
            case com.android.internal.R.styleable.View_id:
                mID = a.getResourceId(attr, NO_ID);
                break;
            case com.android.internal.R.styleable.View_tag:
                mTag = a.getText(attr);
                break;
            case com.android.internal.R.styleable.View_fitsSystemWindows:
                if (a.getBoolean(attr, false)) {
                    viewFlagValues |= FITS_SYSTEM_WINDOWS;
                    viewFlagMasks |= FITS_SYSTEM_WINDOWS;
                }
                break;
            case com.android.internal.R.styleable.View_focusable:
                if (a.getBoolean(attr, false)) {
                    viewFlagValues |= FOCUSABLE;
                    viewFlagMasks |= FOCUSABLE_MASK;
                }
                break;
            case com.android.internal.R.styleable.View_focusableInTouchMode:
                if (a.getBoolean(attr, false)) {
                    viewFlagValues |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE;
                    viewFlagMasks |= FOCUSABLE_IN_TOUCH_MODE | FOCUSABLE_MASK;
                }
                break;
            case com.android.internal.R.styleable.View_clickable:
                if (a.getBoolean(attr, false)) {
                    viewFlagValues |= CLICKABLE;
                    viewFlagMasks |= CLICKABLE;
                }
                break;
            case com.android.internal.R.styleable.View_longClickable:
                if (a.getBoolean(attr, false)) {
                    viewFlagValues |= LONG_CLICKABLE;
                    viewFlagMasks |= LONG_CLICKABLE;
                }
                break;
            case com.android.internal.R.styleable.View_saveEnabled:
                if (!a.getBoolean(attr, true)) {
                    viewFlagValues |= SAVE_DISABLED;
                    viewFlagMasks |= SAVE_DISABLED_MASK;
                }
                break;
            case com.android.internal.R.styleable.View_duplicateParentState:
                if (a.getBoolean(attr, false)) {
                    viewFlagValues |= DUPLICATE_PARENT_STATE;
                    viewFlagMasks |= DUPLICATE_PARENT_STATE;
                }
                break;
            case com.android.internal.R.styleable.View_visibility:
                final int visibility = a.getInt(attr, 0);
                if (visibility != 0) {
                    viewFlagValues |= VISIBILITY_FLAGS[visibility];
                    viewFlagMasks |= VISIBILITY_MASK;
                }
                break;
            case com.android.internal.R.styleable.View_layoutDirection:
                // Clear any layout direction flags (included resolved bits) already set
                mPrivateFlags2 &=
                        ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK);
                // Set the layout direction flags depending on the value of the attribute
                final int layoutDirection = a.getInt(attr, -1);
                final int value = (layoutDirection != -1) ?
                        LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT;
                mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT);
                break;
            case com.android.internal.R.styleable.View_drawingCacheQuality:
                final int cacheQuality = a.getInt(attr, 0);
                if (cacheQuality != 0) {
                    viewFlagValues |= DRAWING_CACHE_QUALITY_FLAGS[cacheQuality];
                    viewFlagMasks |= DRAWING_CACHE_QUALITY_MASK;
                }
                break;
            case com.android.internal.R.styleable.View_contentDescription:
                setContentDescription(a.getString(attr));
                break;
            case com.android.internal.R.styleable.View_labelFor:
                setLabelFor(a.getResourceId(attr, NO_ID));
                break;
            case com.android.internal.R.styleable.View_soundEffectsEnabled:
                if (!a.getBoolean(attr, true)) {
                    viewFlagValues &= ~SOUND_EFFECTS_ENABLED;
                    viewFlagMasks |= SOUND_EFFECTS_ENABLED;
                }
                break;
            case com.android.internal.R.styleable.View_hapticFeedbackEnabled:
                if (!a.getBoolean(attr, true)) {
                    viewFlagValues &= ~HAPTIC_FEEDBACK_ENABLED;
                    viewFlagMasks |= HAPTIC_FEEDBACK_ENABLED;
                }
                break;
            case R.styleable.View_scrollbars:
                final int scrollbars = a.getInt(attr, SCROLLBARS_NONE);
                if (scrollbars != SCROLLBARS_NONE) {
                    viewFlagValues |= scrollbars;
                    viewFlagMasks |= SCROLLBARS_MASK;
                    initializeScrollbars = true;
                }
                break;
            //noinspection deprecation
            case R.styleable.View_fadingEdge:
                if (targetSdkVersion >= ICE_CREAM_SANDWICH) {
                    // Ignore the attribute starting with ICS
                    break;
                }
                // With builds < ICS, fall through and apply fading edges
            case R.styleable.View_requiresFadingEdge:
                final int fadingEdge = a.getInt(attr, FADING_EDGE_NONE);
                if (fadingEdge != FADING_EDGE_NONE) {
                    viewFlagValues |= fadingEdge;
                    viewFlagMasks |= FADING_EDGE_MASK;
                    initializeFadingEdge(a);
                }
                break;
            case R.styleable.View_scrollbarStyle:
                scrollbarStyle = a.getInt(attr, SCROLLBARS_INSIDE_OVERLAY);
                if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
                    viewFlagValues |= scrollbarStyle & SCROLLBARS_STYLE_MASK;
                    viewFlagMasks |= SCROLLBARS_STYLE_MASK;
                }
                break;
            case R.styleable.View_isScrollContainer:
                setScrollContainer = true;
                if (a.getBoolean(attr, false)) {
                    setScrollContainer(true);
                }
                break;
            case com.android.internal.R.styleable.View_keepScreenOn:
                if (a.getBoolean(attr, false)) {
                    viewFlagValues |= KEEP_SCREEN_ON;
                    viewFlagMasks |= KEEP_SCREEN_ON;
                }
                break;
            case R.styleable.View_filterTouchesWhenObscured:
                if (a.getBoolean(attr, false)) {
                    viewFlagValues |= FILTER_TOUCHES_WHEN_OBSCURED;
                    viewFlagMasks |= FILTER_TOUCHES_WHEN_OBSCURED;
                }
                break;
            case R.styleable.View_nextFocusLeft:
                mNextFocusLeftId = a.getResourceId(attr, View.NO_ID);
                break;
            case R.styleable.View_nextFocusRight:
                mNextFocusRightId = a.getResourceId(attr, View.NO_ID);
                break;
            case R.styleable.View_nextFocusUp:
                mNextFocusUpId = a.getResourceId(attr, View.NO_ID);
                break;
            case R.styleable.View_nextFocusDown:
                mNextFocusDownId = a.getResourceId(attr, View.NO_ID);
                break;
            case R.styleable.View_nextFocusForward:
                mNextFocusForwardId = a.getResourceId(attr, View.NO_ID);
                break;
            case R.styleable.View_minWidth:
                mMinWidth = a.getDimensionPixelSize(attr, 0);
                break;
            case R.styleable.View_minHeight:
                mMinHeight = a.getDimensionPixelSize(attr, 0);
                break;
            case R.styleable.View_onClick:
                if (context.isRestricted()) {
                    throw new IllegalStateException("The android:onClick attribute cannot "
                            + "be used within a restricted context");
                }

                final String handlerName = a.getString(attr);
                if (handlerName != null) {
                    setOnClickListener(new OnClickListener() {
                        private Method mHandler;

                        public void onClick(View v) {
                            if (mHandler == null) {
                                try {
                                    mHandler = getContext().getClass().getMethod(handlerName,
                                            View.class);
                                } catch (NoSuchMethodException e) {
                                    int id = getId();
                                    String idText = id == NO_ID ? "" : " with id '"
                                            + getContext().getResources().getResourceEntryName(
                                                id) + "'";
                                    throw new IllegalStateException("Could not find a method " +
                                            handlerName + "(View) in the activity "
                                            + getContext().getClass() + " for onClick handler"
                                            + " on view " + View.this.getClass() + idText, e);
                                }
                            }

droidelStubs.callXMLRegisteredCallback(getContext(), View.this);
                            /*try {
    mHandler.invoke(getContext(), View.this);
                            } catch (IllegalAccessException e) {
                                throw new IllegalStateException("Could not execute non "
                                        + "public method of the activity", e);
                            } catch (InvocationTargetException e) {
                                throw new IllegalStateException("Could not execute "
                                        + "method of the activity", e);
       }*/
                        }
                    });
                }
                break;
            case R.styleable.View_overScrollMode:
                overScrollMode = a.getInt(attr, OVER_SCROLL_IF_CONTENT_SCROLLS);
                break;
            case R.styleable.View_verticalScrollbarPosition:
                mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT);
                break;
            case R.styleable.View_layerType:
                setLayerType(a.getInt(attr, LAYER_TYPE_NONE), null);
                break;
            case R.styleable.View_textDirection:
                // Clear any text direction flag already set
                mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK;
                // Set the text direction flags depending on the value of the attribute
                final int textDirection = a.getInt(attr, -1);
                if (textDirection != -1) {
                    mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection];
                }
                break;
            case R.styleable.View_textAlignment:
                // Clear any text alignment flag already set
                mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK;
                // Set the text alignment flag depending on the value of the attribute
                final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT);
                mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment];
                break;
            case R.styleable.View_importantForAccessibility:
                setImportantForAccessibility(a.getInt(attr,
                        IMPORTANT_FOR_ACCESSIBILITY_DEFAULT));
                break;
            case R.styleable.View_accessibilityLiveRegion:
                setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT));
                break;
        }
    }

    setOverScrollMode(overScrollMode);

    // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet
    // the resolved layout direction). Those cached values will be used later during padding
    // resolution.
    mUserPaddingStart = startPadding;
    mUserPaddingEnd = endPadding;

    if (background != null) {
        setBackground(background);
    }

    // setBackground above will record that padding is currently provided by the background.
    // If we have padding specified via xml, record that here instead and use it.
    mLeftPaddingDefined = leftPaddingDefined;
    mRightPaddingDefined = rightPaddingDefined;

    if (padding >= 0) {
        leftPadding = padding;
        topPadding = padding;
        rightPadding = padding;
        bottomPadding = padding;
        mUserPaddingLeftInitial = padding;
        mUserPaddingRightInitial = padding;
    }

    if (isRtlCompatibilityMode()) {
        // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case.
        // left / right padding are used if defined (meaning here nothing to do). If they are not
        // defined and start / end padding are defined (e.g. in Frameworks resources), then we use
        // start / end and resolve them as left / right (layout direction is not taken into account).
        // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
        // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
        // defined.
        if (!mLeftPaddingDefined && startPaddingDefined) {
            leftPadding = startPadding;
        }
        mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : mUserPaddingLeftInitial;
        if (!mRightPaddingDefined && endPaddingDefined) {
            rightPadding = endPadding;
        }
        mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : mUserPaddingRightInitial;
    } else {
        // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right
        // values defined. Otherwise, left /right values are used.
        // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial
        // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if
        // defined.
        final boolean hasRelativePadding = startPaddingDefined || endPaddingDefined;

        if (mLeftPaddingDefined && !hasRelativePadding) {
            mUserPaddingLeftInitial = leftPadding;
        }
        if (mRightPaddingDefined && !hasRelativePadding) {
            mUserPaddingRightInitial = rightPadding;
        }
    }

    internalSetPadding(
            mUserPaddingLeftInitial,
            topPadding >= 0 ? topPadding : mPaddingTop,
            mUserPaddingRightInitial,
            bottomPadding >= 0 ? bottomPadding : mPaddingBottom);

    if (viewFlagMasks != 0) {
        setFlags(viewFlagValues, viewFlagMasks);
    }

    if (initializeScrollbars) {
        initializeScrollbars(a);
    }

    a.recycle();

    // Needs to be called after mViewFlags is set
    if (scrollbarStyle != SCROLLBARS_INSIDE_OVERLAY) {
        recomputePadding();
    }

    if (x != 0 || y != 0) {
        scrollTo(x, y);
    }

    if (transformSet) {
        setTranslationX(tx);
        setTranslationY(ty);
        setRotation(rotation);
        setRotationX(rotationX);
        setRotationY(rotationY);
        setScaleX(sx);
        setScaleY(sy);
    }

    if (!setScrollContainer && (viewFlagValues&SCROLLBARS_VERTICAL) != 0) {
        setScrollContainer(true);
    }

    computeOpaqueFlags();
}