2012年3月11日 星期日

在Layout XML中的ListView Preview它的List Item效果

<ListView>
<!-- Preview: listitem=@layout/listitem_layout -->
</ListView>

Add activity's view to Layout

// add activity to Layout
FrameLayout container = (FrameLayout) findViewById(R.id.layout);
container.addView(
getLocalActivityManager().startActivity("ViewActivity", new Intent(RootActivity.this , NextActivity.class))
.getDecorView());

2012年3月9日 星期五

Change device orientation, video view not reload

// change device orientation, video view not reload
// "AndroidManifest.xml" file
<activity android:name=".MoviePlayerActivity"
              android:configChanges="orientation" >

2012年2月22日 星期三

Java trim non-number character

// java trim non-number character
System.out.println("@*1#^2$@!34#5ajs67>?<{8_(9SKJDH".replaceAll("\\D", ""));

// output : 123456789

2012年2月17日 星期五

change current resources locale

// change current resources locale
Configuration config = new Configuration();
config.locale = new Locale("zh", "TW");
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());

2012年2月16日 星期四

Get specified service is running

// get specified service is running
ActivityManager myManager=(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
ArrayList runningService = (ArrayList) myManager.getRunningServices(30);
    for(int i = 0 ; i < runningservice.size();i++) {
    
    if(runningService.get(i). service .getClassName().toString().equals("com.xxx.RuningService")) {
            return true;
        }
    }
return false;

2012年2月14日 星期二

Data transport between 2 activity

// data transport between 2 activity
public class RootClassActivity extends Activity {
    public void goToNextPagePress(View view){
        Intent intent = new Intent();
        intent.setClass(RootClassActivity.this, NodeClassActivity.class);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        // requestCode = 0
        // resultCode = 1
    }
}

public class NodeClassActivity extends Activity {

    public void backBtnPress(View view) {
        // return data to persent activity
        this.setResult(1, this.getIntent());
        this.finish();
    }
}

handle button event in list view

// handle button event in list view
<button android:focusable="false" />

2012年2月10日 星期五

Dynamic create view from layout xml

// dynamic create view from layout xml
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.main_layout, null);

2012年2月8日 星期三

Open Android browser

// open web browser
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
this.startActivity(i);

2012年2月5日 星期日

Androids SDK handle large size Bitmap

BitmapFactory.Options op = new BitmapFactory.Options();
// set sample size will scale the image.size/2 op.inSampleSize = 2;

Bitmap bm = BitmapFactory.decodeResource(PaintBushActivity.this.getResources(), R.drawable.img_0218, op);
ImageView displayImg = (ImageView)PaintBushActivity.this.findViewById(R.id.imageView1);
displayImg.setBackgroundDrawable(bd);

2012年2月3日 星期五

Fast get Location in start GPS first time

public class NearByListActivity extends Activity implements LocationListener {
     @Override
     public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.mainLayout);

          // fast get gps location
          locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
          onLocationChanged(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
}

     @Override
     public void onLocationChanged(Location location) {
          // .....
     }
}

2012年1月31日 星期二

Change Activity Orientation

// Activity support screen orientation
"unspecified"  The default value. The system chooses the orientation. The policy it uses, and therefore the choices made in specific contexts, may differ from device to device.
"user"  The user's current preferred orientation.
"behind"  The same orientation as the activity that's immediately beneath it in the activity stack.
"landscape"  Landscape orientation (the display is wider than it is tall).
"portrait"  Portrait orientation (the display is taller than it is wide).
"reverseLandscape"  Landscape orientation in the opposite direction from normal landscape. Added in API level 9.
"reversePortrait"  Portrait orientation in the opposite direction from normal portrait. Added in API level 9.
"sensorLandscape"  Landscape orientation, but can be either normal or reverse landscape based on the device sensor. Added in API level 9.
"sensorPortrait"  Portrait orientation, but can be either normal or reverse portrait based on the device sensor. Added in API level 9.
"sensor"  The orientation is determined by the device orientation sensor. The orientation of the display depends on how the user is holding the device; it changes when the user rotates the device. Some devices, though, will not rotate to all four possible orientations, by default. To allow all four orientations, use "fullSensor".
"fullSensor"  The orientation is determined by the device orientation sensor for any of the 4 orientations. This is similar to "sensor" except this allows any of the 4 possible screen orientations, regardless of what the device will normally do (for example, some devices won't normally use reverse portrait or reverse landscape, but this enables those). Added in API level 9.
"nosensor"  The orientation is determined without reference to a physical orientation sensor. The sensor is ignored, so the display will not rotate based on how the user moves the device. Except for this distinction, the system chooses the orientation using the same policy as for the "unspecified" setting.

// AndroidManifest.xml
<activity android:name="OrientationActivity"
                   android:screenOrientation="portrait" >
</activity>

Android simple play video

// layout.xml
<VideoView android:id="@+id/videoView"
                          android:layout_width="match_parent"
                          android:layout_height="match_parent"
                          android:layout_centerVertical="true" />

// Simple movie player
VideoView videoView = (VideoView) findViewById(R.id.videoView);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
videoView.setVideoURI(Uri.parse("url"));
videoView.start();

Set App full screen

// Set App full screen
import android.view.WindowManager;

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

Android change app title bar

// Edit app title bar
/*
// 1.DEFAULT_FEATURES:系統預設狀態,一般不需要指定
// 2.FEATURE_CONTEXT_MENU:啟用的ContextMenu,預設該項已啟用,一般無需指定
// 3.FEATURE_CUSTOM_TITLE:自定義標題。當需要自定義標題時必須指定。如:標題是一個按鈕時
// 4.FEATURE_INDETERMINATE_PROGRESS:不確定的進度
// 5.FEATURE_LEFT_ICON:標題欄左側的圖標
// 6.FEATURE_NO_TITLE:吳標題
// 7.FEATURE_OPTIONS_PANEL:啟用“選項面板”功能,預設已啟用。
// 8.FEATURE_PROGRESS:進度指示器功能
// 9.FEATURE_RIGHT_ICON:標題欄右側的圖標
*/
this.requestWindowFeature(Window.FEATURE_NO_TITLE);

Make phone call

// AndroidManifest.xml
<uses-permission android:name="android.permission.CALL_PHONE" />

// Call phone
startActivityForResult(new Intent(Intent.ACTION_CALL, Uri.parse("tel:+0000000000000")), 1);

Simple Message Dialog

// Show Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(RootActivity.this);
builder.setMessage(url)
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
            RootActivity.this.finish();
      }
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
      }
});
AlertDialog alert = builder.create();
alert.show();

2012年1月30日 星期一

Android WebView Call Javascript

// WebView call javascript
webView.loadUrl("javascript:alert('Hello World!!');");

Android WebView support javascript

// Set WebView support javascript
webView.getSettings().setJavaScriptEnabled(true);

Android SDK Get Device screen size pixels

DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics);
dm.widthPixels; // Width Pixels
dm.heightPixels; // Height Pixels

Animation : View/Layout AlphaAnimation

AlphaAnimation alphaAnimation = new AlphaAnimation(0.0f, 1.0f);
alphaAnimation.setDuration(250);
alphaAnimation.setRepeatMode(1);
alphaAnimation.setAnimationListener(new AnimationListener(){

    @Override
    public void onAnimationEnd(Animation animation) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAnimationRepeat(Animation animation) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAnimationStart(Animation animation) {
        // TODO Auto-generated method stub

    }

});
contentView.startAnimation(alphaAnimation);

Android SDK Overlap View on other View

原來只要在底層用RelativeLayout,
就可以在RelativeLayout上重疊其他Layout了.

Get Android Device/App Info

// Get Model Name
import android.os.Build;
Build.MODEL

// Get Device ID
import android.provider.Settings.Secure;
Secure.getString(getContentResolver(), Secure.ANDROID_ID);

// Get app version name
String versionName = "0";
try
{
   versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
}
catch(NameNotFoundException e)
{}

Android pass extra data to next Activity

RootClassActivity :
public class RootClassActivity extends Activity {
   public void goToNextPagePress(View view) {
      Intent intent = new Intent();
      intent.setClass(RootClassActivity.this, NodeClassActivity.class);
      intent.putExtra("type", 0); 
      Bundle bundle = new Bundle(); 
      bundle.putInt("value", 1); 
      intent.putExtras(bundle); 
      startActivity(intent);
   }
}

NodeClassActivity :
public class NodeClassActivity extends Activity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      Intent intent = this.getIntent(); 
      int type = intent.getIntExtra("type", 0); 
      Bundle bundle = intent.getExtras(); 
      int value = bundle.getInt("value");
   }

   public void backBtnPress(View view) {
      NodeClassActivity.this.finish();
   }
}

2012年1月29日 星期日

Single press button show Android Context Menu

public void onCreate(Bundle savedInstanceState)
{
      Button reloadBtn = (Button)findViewById(R.id.reloadBtn);
      // register button for context menu
      // just call this method, you must be long press button to show context menu
      registerForContextMenu(reloadBtn);
}

public void reloadBtnPress(View view)
{
      // register menu and call open context menu
      // you can custom to show menu
      this.openContextMenu(view);
}

2012年1月21日 星期六

設定UILocalNotification重複星期日至六

iOS內的時間App重複設定可以設為星期日至六,
我想它是用UILocalNotification設定重複提示所做成的。
以下是實現代碼
// 獲得當前的時分秒
NSDate* now = [NSDate date];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"HH:mm:ss"];
NSString* nowTime = [formatter stringFromDate:now];
NSDate* nowDate = [formatter dateFromString:nowTime];
[formatter release];

NSArray* strArr = [NSArray arrayWithObjects:@"Sunday", @"Monday", @"Tuesday", @"Wednesday", @"Thursday", @"Friday", @"Saturday", nil];
for(NSUInteger i = 0; i < 7; i++)
{
  UILocalNotification* localNotification = [[UILocalNotification alloc] init];
  if (localNotification == nil)
    continue;
  // 設定提示日期,本來日期已過Local Notification是不可被schedule的,
  // 重複是例外,我以1970年1月1日為單位加3天就是星期天,
  // 再加上今天我時間差,就可以每天都是在同一時間來重複提示
  localNotification.fireDate = [NSDate dateWithTimeIntervalSince1970:60*60*24*(3+i)+[nowDate timeIntervalSince1970]];
  localNotification.alertBody = [strArr objectAtIndex:i];

  // 設定每星期也重複
  localNotification.repeatCalendar = [NSCalendar currentCalendar];   localNotification.repeatInterval = NSWeekdayCalendarUnit;

  localNotification.alertAction = @"View";
  localNotification.soundName = UILocalNotificationDefaultSoundName;   [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];   [localNotification release];
}