2013年5月29日 星期三

How to check if the application is installed or not in android programmatically [duplicate]


22down voteaccepted
Try with this,
 public class Example extends Activity
    {
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            //Put the package name here...
            boolean installed  =   appInstalledOrNot("com.Ch.Example.pack");  
            if(installed)
            {
            //This intent will help you to launch if the package is already installed
            Intent LaunchIntent = getPackageManager()
                .getLaunchIntentForPackage("com.Ch.Example.pack");
        startActivity(LaunchIntent);


                      System.out.println("App already installed om your phone");


            }
            else
            {
                System.out.println("App is not installed om your phone");
            }
        }
        private boolean appInstalledOrNot(String uri)
        {
            PackageManager pm = getPackageManager();
            boolean app_installed = false;
            try
            {
                   pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
                   app_installed = true;
            }
            catch (PackageManager.NameNotFoundException e)
            {
                   app_installed = false;
            }
            return app_installed ;
    }
    }
share|improve this answer

2013年5月28日 星期二

Detect WIFI ON/OFF

ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
   // Do whatever
Toast.makeText(getApplicationContext(), "Wifi is on",Toast.LENGTH_SHORT).show();
}

hide soft keyboard

InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

--------------or-----------------

 <activity
            android:name="today.is.future.profile073.NewProfile"
            android:label="newprofile"
            android:theme="@android:style/Theme.Holo.NoActionBar"
            android:windowSoftInputMode="stateHidden" >
        </activity>

change input method

private void showInputMethodPicker() { InputMethodManager imeManager = (InputMethodManager) getApplicationContext().getSystemService(INPUT_METHOD_SERVICE); if (imeManager != null) { imeManager.showInputMethodPicker(); } else { Toast.makeText(this, R.string.not_possible_im_picker, Toast.LENGTH_LONG).show(); } }

2013年5月22日 星期三

read_ex()


protected String read_ex(String string, String string2) {
// TODO Auto-generated method stub
File sdcard = new File(Environment.getExternalStorageDirectory() + "/"
+ string);

// Get the text file
File file = new File(sdcard, string2);

// Read text from file
StringBuilder text = new StringBuilder();

try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;

while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e) {
// You'll need to add proper error handling here
}
return text.toString().substring(0, text.toString().length() - 1);
}

2013年5月21日 星期二

delete folder


void DeleteRecursive(File fileOrDirectory) {
   if (fileOrDirectory.isDirectory())
       for (File child : fileOrDirectory.listFiles())
           DeleteRecursive(child);

   fileOrDirectory.delete();
}

write_ex()



protected void write_ex(String string, String string2, String string3) {
// TODO Auto-generated method stub
//This will get the SD Card directory and create a folder named MyFiles in it.
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/"+string);
directory.mkdirs();

//Now create the file in the above directory and write the contents into it
File file = new File(directory, string2);
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(string3);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
osw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

GPS CONTROL


75down voteaccepted
the GPS can be toggled by exploiting a bug in the power manager widget. see this xda thread for discussion.
here's some example code i use
private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}
use the following to test if the existing version of the power control widget is one which will allow you to toggle the gps.
private boolean canToggleGPS() {
    PackageManager pacman = getPackageManager();
    PackageInfo pacInfo = null;

    try {
        pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
    } catch (NameNotFoundException e) {
        return false; //package not found
    }

    if(pacInfo != null){
        for(ActivityInfo actInfo : pacInfo.receivers){
            //test if recevier is exported. if so, we can toggle GPS.
            if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
                return true;
            }
        }
    }

    return false; //default
}
share|improve this answer

2013年5月20日 星期一

vibrate


Try:
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(500);
Note:
Don't forget to include permission in AndroidManifest.xml file:
<uses-permission android:name="android.permission.VIBRATE"/>
share|improve this answer

2013年5月19日 星期日

Change system screen brightness, using android.provider.Settings.System.SCREEN_BRIGHTNESS


Change system screen brightness, using android.provider.Settings.System.SCREEN_BRIGHTNESS

Last exercise "Change Android Screen Brightness, LayoutParams.screenBrightness" for my app only. On order to change system screen brightness, we can use the code:

android.provider.Settings.System.putInt(getContentResolver(),
android.provider.Settings.System.SCREEN_BRIGHTNESS,
SysBackLightValue);

Change system screen brightness

To access Settings.System.SCREEN_BRIGHTNESS, we have to modify AndroidManifest.xml to grant premission of "android.permission.WRITE_SETTINGS".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exercise.AndroidScreenBrightness"
    android:versionCode="1"
    android:versionName="1.0">
  <application android:icon="@drawable/icon" android:label="@string/app_name">
      <activity android:name=".AndroidScreenBrightness"
                android:label="@string/app_name">
          <intent-filter>
              <action android:name="android.intent.action.MAIN" />
              <category android:name="android.intent.category.LAUNCHER" />
          </intent-filter>
      </activity>

  </application>
  <uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
</manifest>


main code
package com.exercise.AndroidScreenBrightness;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

public class AndroidScreenBrightness extends Activity {
  /** Called when the activity is first created. */

float BackLightValue = 0.5f; //dummy default value

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
    
      SeekBar BackLightControl = (SeekBar)findViewById(R.id.backlightcontrol);
      final TextView BackLightSetting = (TextView)findViewById(R.id.backlightsetting);
      Button UpdateSystemSetting = (Button)findViewById(R.id.updatesystemsetting);
    
      UpdateSystemSetting.setOnClickListener(new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
  
   int SysBackLightValue = (int)(BackLightValue * 255);
  
   android.provider.Settings.System.putInt(getContentResolver(),
     android.provider.Settings.System.SCREEN_BRIGHTNESS,
     SysBackLightValue);
  
  }});
    
      BackLightControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){

  @Override
  public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
   // TODO Auto-generated method stub
   BackLightValue = (float)arg1/100;
   BackLightSetting.setText(String.valueOf(BackLightValue));
  
   WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
   layoutParams.screenBrightness = BackLightValue;
   getWindow().setAttributes(layoutParams);

  
  }

  @Override
  public void onStartTrackingTouch(SeekBar arg0) {
   // TODO Auto-generated method stub
  
  }

  @Override
  public void onStopTrackingTouch(SeekBar arg0) {
   // TODO Auto-generated method stub
  
  }});
  }
}


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  />
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Set BackLight of the App"
  />
<SeekBar
  android:id="@+id/backlightcontrol"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_margin="10px"
  android:max="100"
  android:progress="50"
  />
<TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:id="@+id/backlightsetting"
  android:text="0.50"
  />
<Button
  android:id="@+id/updatesystemsetting"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Update Settings.System.SCREEN_BRIGHTNESS"
  />
</LinearLayout>

------------------------------------------------------------

float BackLightValue = Integer.valueOf(read_in(
filename, "brightness").split("\n")[1]);
int SysBackLightValue = (int) (BackLightValue / 100 * 245) + 10;
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS_MODE,
Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
android.provider.Settings.System.putInt(getContentResolver(),

android.provider.Settings.System.SCREEN_BRIGHTNESS,SysBackLightValue);
Related Posts Plugin for WordPress, Blogger...