2012年11月9日 星期五

[Android]設定URL圖片給ImageView

private Bitmap myBitmap;
URL myImageURL = null;


try {

myImageURL = new URL(imageURL);

HttpURLConnection connection = (HttpURLConnection)myImageURL .openConnection();

connection.setDoInput(true);

connection.connect();

InputStream input = connection.getInputStream();

myBitmap = BitmapFactory.decodeStream(input);

}

2012年10月8日 星期一

PHP 字元轉換二、八、十、十六進位

二進位二進制(B,Binary)00000010=2
八進位八進制(O,Octal)00000010=8
十進位十進制(D,Decimalist)00000010=10
十進位十六進制(H,Hex)00000010=16


Binary 跟 ASCII互轉

 
function asc2bin($str) {
$text_array = explode("\r\n", chunk_split($str, 1));
for ($n = 0; $n < count($text_array) - 1; $n++) {
$newstring .= substr("0000".base_convert(ord($text_array[$n]), 10, 2), -8);
}
$newstring = chunk_split($newstring, 8, " ");
return $newstring;
}

function bin2asc($str) {
$str = str_replace(" ", "", $str);
$text_array = explode("\r\n", chunk_split($str, 8));
for ($n = 0; $n < count($text_array) - 1; $n++) {
$newstring .= chr(base_convert($text_array[$n], 2, 10));
}
return $newstring;
}

ASCII 與 HEX互轉
 
function asc2hex($str) {
return chunk_split(bin2hex($str), 2, " ");
}

function hex2asc($str) {
$str = str_replace(" ", "", $str);
for ($n=0; $n<strlen($str); $n+=2) {
$newstring .= pack(&quot;C&quot;, hexdec(substr($str, $n, 2)));
}

return $newstring;
}

Binary 與 HEX互轉
 
function binary2hex($str) {
$str = str_replace(" ", "", $str);
$text_array = explode("\r\n", chunk_split($str, 8));
for ($n = 0; $n < count($text_array) - 1; $n++) {
$newstring .= base_convert($text_array[$n], 2, 16);
}
$newstring = chunk_split($newstring, 2, " ");
return $newstring;
}

function hex2binary($str) {
$str = str_replace(" ", "", $str);
$text_array = explode("\r\n", chunk_split($str, 2));
for ($n = 0; $n < count($text_array) - 1; $n++) {
$newstring .= substr("0000".base_convert($text_array[$n], 16, 2), -8);
}
$newstring = chunk_split($newstring, 8, " ");
return $newstring;
}
引用:Nightmare的胡言亂語-利用PHP來做字元碼轉換(Binary、ASCII、HEX互轉)

2012年9月24日 星期一

C#窗体淡入淡出

//淡入
public int state = 0;private void f2_Load(object sender, EventArgs e)
{
this.Opacity = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (state == 0)
{
this.Opacity += 0.02;if (this.Opacity == 1)
{
state
= 1;
timer1.Enabled
= false;
}
}
else
{
this.Opacity = Opacity - 0.02;if (this.Opacity == 0)
{
Application.ExitThread();
}
}
}
//退出
private void f2closing(object sender, FormClosingEventArgs e)
{
e.Cancel
= true;
timer1.Start();
}

2012年7月31日 星期二

android get apk version

// use to get this apk version which write in its own AndroidManifest.xml
    protected String getVersion() {
        PackageInfo pInfo = null;
        try {
            pInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
        return pInfo.versionName;
    }

2012年7月24日 星期二

android MATCH_PARENT

MATCH_PARENT

從API Level 8(即Android 2.2)開始, Android API 的 layout_width 和 layout_height 新增 "MATCH_PARENT", 其實"MATCH_PARENT"基本上與"FILL_PARENT"相同("FILL_PARENT"已過時); 它們的數值都是-1(0xffffffff), 意味著該視圖盡可能填滿它的父對象減去padding的寬度或高度.


fill_parent 就是让控件宽或者高占全屏,而wrap_content是让控件的高或宽仅仅把控件里的内容包裹住,而不是全屏

2012年7月22日 星期日

App 提交 iTunes Store for Xcode 4.3.3

第一次提交,新上架
網站流程:
  1. 登入 iOS Dev Center - Apple Developer
  2. 點選 iTunes Connect
  3. 點選 Manage Your Applications
  4. 點選 Add New App
  5. 填寫 App Name,可以是中文
  6. 填寫 SKU Number,替你的 app 取一個 unique 的值
  7. 點選 You can register a new Bundle ID here.
  8. 會來到 iOS Provisioning Portal 的 Create App ID 頁面
  9. Bundle Identifier (App ID Suffix) 就取個類似 com.company.app_name 的名字
  10. 回到 Add New App 的頁面,選擇剛剛建立的 App ID
  11. 然後填了好幾頁的關於 app detail 的表格,上傳 icon 和截圖什麼的
  12. 點選 Ready to Upload Binary
  13. 當你看到 Status 是 Waiting For Upload 之後
申請 Distribution Certificate:
  1. Launchpad > 工具程式 > Keychain Access
  2. Keychain Access > Preferences,把 OCSP 和 CRL 設為 Off
  3. Keychain Access > Certificate Assistant > Request Certificate from Authority
  4. 勾選 Saved to Disk 和 Let me specify key pair information
  5. 選擇 key size of 2048 bits 和 RSA algorithm
  6. 會在桌面產生一個 xxx.xxx.certSigningRequest
  7. 登入 iOS Provisioning Portal
  8. 點選 Certificates > Distribution
  9. 如果 Current Distribution Certificate 底下已經有一個 Certificate 的話,你可以 Revoke 它
  10. 用剛剛產生的 xxx.certSigningRequest 去 request 新的 Certificate
  11. 下載 ios_distribution.cer 並放入 Keychain

2012年7月16日 星期一

c# AxWMPLib.AxWindowsMediaPlayer

AxWMPLib.AxWindowsMediaPlayer

MediaPlayer控制項屬性
AllowChangeDisplaySize 返回或設置最終用戶是否能設置顯示尺寸(邏輯型)
AllowScan
返回或設置是否允許掃描(邏輯型)
AnimationAtStart
返回或設置控制項開始播放之前是否先播放一個動畫序列(邏輯型)
AudioStream
返回或設置音頻流的編號(用於多音頻流的剪輯,默認爲-1)(長整型)
AutoRewind
返回或設置媒體文件播放完畢後是否自動回繞(邏輯型)
AutoSize
返回或設置是否自動調整控制項大小來適應載入的媒體(邏輯型)
AutoStart
返回或設置在載入媒體文件之後是否自動開始播放(邏輯型)
Balance
返回或設置指定身歷聲媒體文件的播放聲道(-10000爲左聲道,10000爲右聲道,0爲身歷聲)(長整型)
Bandwidth
返回或設置當前文件的帶寬(長整型)
BaseURL
返回基本的 HTTP URL(字串)
BufferingCount
返回媒體文件重播時緩衝的總時間(長整型)
BufferingProgress
返回緩衝完成的百分比(長整型)
BufferingTime
返回緩衝的時間(雙精度型)
CanPreview
返回或設置當前顯示的剪輯是能否被預覽(邏輯型)
CanScan
返回或設置當前文件是否支援快進或快退(邏輯型)
CanSeek
返回或設置當前文件是否能搜索並定位到某個時間(邏輯型)
CanSeekToMarkers
返回或設置文件是否支援搜索到標簽(邏輯型)
CaptioningID
返回在標題中顯示的幀或控制項的名稱(字串)
ChannelDescription
返回電臺的描述(字串)
ChannelName
返回電臺的名稱(字串)
ChannelURL
返回電臺的元文件的位置(字串)
ClickToPlay
返回或設置是否可以通過點擊圖像暫停或播放剪輯(邏輯型)
ClientID
返回用戶端唯一的識別字(字串)
CodecCount
返回文件使用的可安裝的 codecs 的個數(長整型)
ContactAddress
返回電臺的聯繫地址(字串)
ContactEmail
返回電臺的聯繫電子郵件地址(字串)
ContactPhone
返回電臺的聯繫電話(字串)
CreationDate
返回剪輯的創建日期(日期型)
CurrentMarker
返回或設置當前書簽號碼(長整型)
CurrentPosition
返回或設置剪輯的當前位置(雙精度型)
CursorType
返回或設置指標類型(長整型)
DefaultFrame
返回或設置控制項的默認目標 Http (字串)
DisplayBackColor
返回或設置顯示面板的背景色(OLE_COLOR )
DisplayForeColor
返回或設置顯示面板的前景色(OLE_COLOR )
DisplayMode
返回或設置顯示面板是否用秒或幀的形式顯示當前位置(MPDisplayModeConstants )
DisplaySize
返回或設置圖像顯示視窗的大小(MPDisplaySizeConstant )
Duration
返回或設置剪輯剪輯的播放時間(雙精度型)
EnableContextMenu
返回或設置是否允許使用上下文功能表(邏輯型)
Enabled
返回或設置控制項是否可用(邏輯型)
EnableFullScreenControls
返回或設置全螢幕控制是否可用(邏輯型)
EnablePositionControls
返回或設置位置控制是否可用(邏輯型)
EnableTracker
返回或設置搜索欄控制是否可用(邏輯型)
ErrorCode
返回當前錯誤代碼(長整型)
ErrorCorrection
返回當前剪輯的錯誤修正類型(長整型)
ErrorDescription
返回當前錯誤的描述(字串)
FileName
返回或設置要播放的剪輯的檔案名稱(字串)
HasError
返回控制項是否發生錯誤(邏輯型)
HasMultipleItems
返回或設置控制項是否包含某些多重專案的內容(邏輯型)
ImageSourceHeight
返回或設置當前剪輯的原始圖像高度(長整型)
ImageSourceWidth
返回或設置當前剪輯的原始圖像寬度(長整型)
InvokeURLs
返回或設置 URL 是否自動發送請求(邏輯型)
IsBroadcast
返回或設置源是否進行廣播(邏輯型)
IsDurationValid
返回或設置持續時間值是否有效(邏輯型)
Language
返回或設置用於本地化語言支援的當前區域語言(長整型)
LostPackets
返回丟失的資料包數量(長整型)
MarkerCount
返回文件書簽的數量(長整型)
Mute
返回或設置控制項是否播放聲音(邏輯型)
OpenState
返回控制項的內容源狀態(長整型)
PlayCount
返回或設置一個剪輯播放的次數(長整型)
PlayState
返回控制項的當前操作狀態(長整型)
PreviewMode
返回或設置控制項是否處在預覽模式(邏輯型)
Rate
返回或設置重播幀頻(雙精度型)
ReadyState
返回控制項是否準備就緒(ReadyStateConstant )
ReceivedPackets
返回已接收到的資料包的數量(長整型)
ReceptionQuality
返回最後 30 秒接收到的資料包的百分比(長整型)
RecoveredPackets
返回已轉換的資料包的數量(長整型)
SAMIFileName
返回或設置 closed-captioning 檔案名(字串)
SAMILang
返回或設置 closed captioning 語言(字串)
SAMIStyle
返回或設置 closed captioning 風格(字串)
SelectionEnd
返回或設置流的結束位置(雙精度型)
SelectionStart
返回或設置流的起始位置(雙精度型)
SendErrorEvents
返回或設置控制項是否發送錯誤事件(邏輯型)
SendKeyboardEvents
返回或設置控制項是否發送鍵盤事件(邏輯型)
SendMouseClickEvents
返回或設置控制項是否發送滑鼠單擊事件(邏輯型)
SendMouseMoveEvents
返回或設置控制項是否發送滑鼠移動事件(邏輯型)
SendOpenStateChangeEvents
返回或設置控制項是否發送打開狀態改變事件(邏輯型)
SendPlayStateChangeEvents
返回或設置控制項是否發送播放狀態改變事件(邏輯型)
SendWarningEvents
返回或設置控制項是否發送警告事件(邏輯型)
ShowAudioControls
返回或設置是否顯示音頻控制(邏輯型)
ShowCaptioning
返回或設置是否顯示字幕(邏輯型)
ShowControls
返回或設置控制面板是否可見(邏輯型)
ShowDisplay
返回或設置是否顯示顯示面板(邏輯型)
ShowGotoBar
返回或設置是否顯示跳轉欄(邏輯型)
ShowPositionControls
返回或設置是否顯示位置控制(邏輯型)
ShowStatusBar
返回或設置是否顯示狀態欄(邏輯型)
ShowTracker
返回或設置是否顯示搜索欄(邏輯型)
SourceLink
返回內容文件的路徑(字串)
SourceProtocol
返回用於接收資料的協定(長整型)
StreamCount
返回媒體幀的數量(長整型)
TransparentAtStart
返回或設置在開始播放之前和停止之後控制項是否透明(邏輯型)
VideoBorder3D
返回或設置視頻邊框是否顯示爲 3D 效果(邏輯型)
VideoBorderColor
返回或設置視頻邊框的顔色(OLE_顔色)
VideoBorderWidth
返回或設置視頻邊框的寬度(長整型)
Volume
返回或設置音量(長整型)
屬性/方法名/說明:

[基本屬性]
  

http://www.blogger.com/String;
 指定媒體位置,本機或網路位址

uiMode:String;
 播放器介面模式,可爲Full, Mini, None, Invisible

playState:integer;
 播放狀態,1=停止,2=暫停,3=播放,6=正在緩衝,9=正在連接,10=準備就緒

enableContextMenu:Boolean;
 啓用/禁用右鍵功能表

fullScreen:boolean;
 是否全屏顯示

[controls]
 wmp.controls //播放器基本控制

controls.play;
 播放

controls.pause;
 暫停

controls.stop;
 停止

controls.currentPosition:double;
 當前進度

controls.currentPositionString:string;
 當前進度,字串格式。如“00:23”

controls.fastForward;
 快進

controls.fastReverse;
 快退

controls.next;
 下一曲

controls.previous;
 上一曲

[settings]
 wmp.settings //播放器基本設置

settings.volume:integer;
 音量,0-100

settings.autoStart:Boolean;
 是否自動播放

settings.mute:Boolean;
 是否靜音

settings.playCount:integer;
 播放次數

[currentMedia]
 wmp.currentMedia //當前媒體屬性

currentMedia.duration:double;
 媒體總長度

currentMedia.durationString:string;
 媒體總長度,字串格式。如“03:24”

currentMedia.getItemInfo(const string);
 獲 取當前媒體資訊"Title"=媒體標題,"Author"=藝術家,"Copyright"=版權資訊,"Description"=媒體內容描述, "Duration"=持續時間(秒),"FileSize"=文件大小,"FileType"=文件類型,"sourceURL"=原始地址

currentMedia.setItemInfo(const string);
 通過屬性名設置媒體資訊

currentMedia.name:string;
 同 currentMedia.getItemInfo("Title")

[currentPlaylist]
 wmp.currentPlaylist //當前播放列表屬性

currentPlaylist.count:integer;
 當前播放列表所包含媒體數

currentPlaylist.Item[integer];
 獲取或設置指定專案媒體資訊,其子屬性同wmp.currentMedi



2012年7月15日 星期日

[C#]使用 Windows Media Player

要在WinForm裡內嵌一個Windows Media Player
1.先去下載Windows Media Player SDK(可以在Help裡面找到需要的說明)

2.然後在專案中加入WMP的Lib
在 Windows\system32 底下的wmp.dll

3.然後設計WinForm時在左邊的工具箱右鍵點選"選擇項目"
COM元件中把WMP加入
之後就可以把WMP拉到WinForm中囉

例:
using WMPLib;
....

namespace MyProject
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
           
            // 播放歌曲
            axWMP.URL = @"D:\Music\02.AVRIL LAVIGNE 酷到骨子裡 MY HAPPY ENDING.mp3";
            // 設定重複播放
            //axWMP.settings.setMode("loop", true);
            // 設定隨機播放
            //axWMP.settings.setMode("shuffle", true);
        }
    }
}

2012年7月13日 星期五

Android Intents - Tutorial

Android Intents - Tutorial




Lars Vogel

Version 2.6
17.04.2012
Revision History
Revision 0.120.07.2010LarsVogel
Created
Revision 0.2 - 2.619.07.2010 - 17.04.2012LarsVogel
bug fixes and enhancements
Using Intents in Android
This tutorials describes what Intents are and how to use them in Android. It is based on Eclipse 3.7, Java 1.6 and Android 4.0.4 (Ice Cream Sandwich).

1. Android Intents

1.1. Overview

Intents are asynchronous messages which allow Android components to request functionality from other components of the Android system. For example an Activity can send an Intents to the Android system which starts another Activity.
Therefore Intents allow to combine loosely coupled components to perform certain tasks.
Intents can be used to signal to the Android system that a certain event has occurred. Other components in Android can register to this event and will get notified.
Intents are instances of the android.content.Intent class.
Intents are send to the Android system. Depending on how the Intent was constructed the Android system will run an receiver determination and determine what to do.
An Intent can also contain data. This data can be used by the receiving component. For example your application can calls via an Intent a browser component. As data is it may send the URL to the browser component.
Android supports explicit and implicit Intents.

1.2. Explicit Intents

Explicit Intents explicitly names the component which should be called by the Android system, by using the Java class as identifier.
The following shows an explicit Intent. If that Intent is correctly send to the Android system, it will start the associated class.

Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
i.putExtra("Value2", "This value two ActivityTwo"); 

Explicit Intents are typically used within on application as the classes in an application are controlled by the application developer.

1.3. Implicit Intents

Implicit Intents do not specify the Java class which should be called. They specify the action which should be performed and optionally an URI which should be used for this action.
For example the following tells the Android system to view a webpage. Typically the web browser is registered to this Intent but other component could also register themself to this event.

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.vogella.com")); 
If these Intents are send to the Android system it searches for all components which are registered for the specific action and the data type.
If only one component is found, Android starts this component directly. If several components are identifier by the Android system, the user will get an selection dialog and can decide which component should be used for the Intent.

1.4. Data Transfer

An implicit Intent contains the Action and optional the URI. The receiving component can get this information via the getAction() and getData() methods.
Explicit and implicit Intents can also contain additional data. This data call be filled by the component which creates the Intent. It can and can get extracted by the component which receives the Intent.
The component which creates the Intent can add data to it via the overloaded putExtra() method. Extras are key/value pairs; the key is always a String. As value you can use the primitive data types (int, float,..), String, Bundle, Parceable and Serializable.
For example you can trigger all components which have been registered to send some data via the new Intent(Intent.ACTION_SEND) This Intent determines possible receivers via the type. What is send it defined via the putExtra method. You can use any String as key, the following uses the keys which are predefined for the ACTION_SEND intent.

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(android.content.Intent.EXTRA_TEXT, "News for you!");
startActivity(intent); 

The component which receives the Intent can use the getIntent().getExtras() method call to get the extra data.

Bundle extras = getIntent().getExtras();
if (extras == null) {
  return;
  }
// Get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
 // Do something with the data
} 

2. Using Intents to call Activities

2.1. Calling Activities

If you send an Intent to the Android system, Android requires that you tell it to which type of component your Intent should be send.
To start an Activity use the method startActivity(Intent). This method is defined on the Context object and available in every Activity object.
If you call an Activity with the startActivity(Intent) method the caller requires no result from the called Activity.

2.2. Calling Sub-Activities for result data

If you need some information from the called Activity use the startActivityForResult() method.

public void onClick(View view) {
 Intent i = new Intent(this, ActivityTwo.class);
 i.putExtra("Value1", "This value one for ActivityTwo ");
 i.putExtra("Value2", "This value two ActivityTwo");
 // Set the request code to any code you like, you can identify the
 // callback via this code
 startActivityForResult(i, REQUEST_CODE);
} 

If you use the startActivityForResult() method then the started Activity is called a Sub-Activity.
If the Sub-Activity is finished it can send data back to its caller via Intent. This is done in the finish() method.

@Override
public void finish() {
 // Prepare data intent 
 Intent data = new Intent();
 data.putExtra("returnKey1", "Swinging on a star. ");
 data.putExtra("returnKey2", "You could be better then you are. ");
 // Activity finished ok, return the data
 setResult(RESULT_OK, data);
 super.finish();
} 

Once the Sub-Activity finished, the onActivityResult() method in the calling Activity will be called.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
  if (data.hasExtra("returnKey1")) {
   Toast.makeText(this, data.getExtras().getString("returnKey1"),
    Toast.LENGTH_SHORT).show();
  }
 }
} 

3. Defining Intent Filters

3.1. Overview

If an Intent is send to the Android system, it will determine suitable applications for this Intent. If several components have been registered for this type of Intent, Android offers the user the choice to open one of them.
This determination is based on IntentFiltes. An IntentFilter specifies the types of Intent that an activity, service, or broadcast receiver can respond to. An IntentFilter declares the capabilities of a component. It specifies what an Activity or Service can do and what types of broadcasts a Rseceiver can handle. It allow the corresponding component to receive Intents of the declared type.
IntentFilters are typically defined via the AndroidManifest.xml file. For BroadcastReceiver it is also possible to define them in coding. An IntentFilters is defined by its category, action and data filters. It can also contain additional metadata.
The following will register an Activity for the Intent which is triggered when someone wants to open a webpage.

<activity android:name=".BrowserActivitiy" 
          android:label="@string/app_name">
  <intent-filter>
     <action android:name="android.intent.action.VIEW" />
     <category android:name="android.intent.category.DEFAULT" />
     <data android:scheme="http"/> 
  </intent-filter>
</activity> 

This is an example how you could define an Intent receiver for the ACTION.SEND Intent.

<activity
 android:name=".ActivityTest"
    android:label="@string/app_name" >
    <intent-filter>
      <action android:name="android.intent.action.SEND" />
      
      <category android:name="android.intent.category.DEFAULT" />

      <data android:mimeType="text/plain" />
    
    </intent-filter>

</activity> 

If a component does not define Intent filters, it can only be called by explicit Intents.
The following example will register an Activity for the ACTION_SEND intent for the "text/plain" mime type.

<activity
 android:name=".ActivityTest"
    android:label="@string/app_name" >
    <intent-filter>
      <action android:name="android.intent.action.SEND" />
      
      <category android:name="android.intent.category.DEFAULT" />

      <data android:mimeType="text/plain" />
    
    </intent-filter>

</activity> 

3.2. Restrictions as of Android 3.1

As of Android 3.1 the Android system will by default exclude all BroadcastReceiver from receiving Intents if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage Application).
This is an additional security features as the user can be sure that only the applications he started will receive broadcast Intents.

4. Intents as event triggers

Intents can also be used to send broadcast messages into the Android system. BroadcastReceivers can register to event and will get notified if such an event is triggered.
Your application can register to system events, e.g. a new email has arrived, system boot is complete or a phone call is received and react accordingly.
As said earlier, since Android version 3.1 the Android system will per default exclude all BroadcastReceiver from receiving Intents if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage Application).

5. Share Intent and ShareActionProvider

As of Android 4.0 you can also add an Action Provider to your ActionBar which allows to share. For this you have to define a special menu entry and assign an Intent which contain the sharing data to it in your Activity.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

   <item android:id="@+id/menu_share"
          android:title="Share"
          android:showAsAction="ifRoom"
          android:actionProviderClass="android.widget.ShareActionProvider" />
    <item
        android:id="@+id/item1"
        android:showAsAction="ifRoom"
        android:title="More entries...">
    </item>

</menu> 


@Override
public boolean onCreateOptionsMenu(Menu menu) {
 getMenuInflater().inflate(R.menu.mymenu, menu);
 // provider is a field in your Activity
 provider = (ShareActionProvider) menu.findItem(R.id.menu_share)
  .getActionProvider();
 setShareIntent();
 return true;
}


public void setShareIntent() {
 Intent intent = new Intent(Intent.ACTION_SEND);
 intent.setType("text/plain");
 intent.putExtra(Intent.EXTRA_TEXT, "Message");
 provider.setShareIntent(intent);
} 

Unfortunately this does not seem to work in the Android emulator, see Bug report for details .

6. Finding out if an Intent is available

Sometimes you want to find if an application has registered for a certain intent. For example you want to check if a certain receiver is available and if you enable some functionality in your app.
This can be done via checking the PackageManager. The following code checks if an Intent exists. You can check via this method for Intent and change your application behavior accordingly for example disable or hide menu items.

public boolean isIntentAvailable(Context context, String action) {
    final PackageManager packageManager = context.getPackageManager();
    final Intent intent = new Intent(action);
    List<ResolveInfo> resolveInfo =
            packageManager.queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
   if (resolveInfo.size() > 0) {
     return true;
    }
   return false;
} 

7. Prerequisites for this tutorial

The following assumes that you have already basic knowledge in Android development. Please check the Android development tutorial to learn the basics.

Android – Using Intents to Open Files

Do you want to open from your code some mp3 or image file with the default media player/image viewing application? Use this:
?
01
02
03
04
05
06
07
08
09
10
File videoFile2Play = new File("/sdcard/nice_movie.mpeg");
Intent i = new Intent();
i.setAction(android.content.Intent.ACTION_VIEW);
i.setDataAndType(Uri.fromFile(videoFile2Play), "video/mpeg");
startActivity(i);
File musicFile2Play = new File("/sdcard/some_file.mp3");
Intent i2 = new Intent();
i2.setAction(android.content.Intent.ACTION_VIEW);
i2.setDataAndType(Uri.fromFile(musicFile2Play), "audio/mp3");
startActivity(i2);
If you want to open some other supported files with their own applications take a look at the table below to see the exact types you should use. If you don’t find in the table the file extension you want don’t worry, use the type String with the wild card character like this (and if your system supports that file it will be loaded by the appropriate application):
?
1
2
3
File videoFile2Play2 = new File("/sdcard/nice_movie2.mp4");
i.setDataAndType(Uri.fromFile(videoFile2Play2), "video/*");
startActivity(i);

ExtensionMIME Type
Android Application.apkapplication/vnd.android.package-archive
Text.txttext/plain
.csvtext/csv
.xmltext/xml
Web related.htmtext/html
.htmltext/html
.phptext/php
Image.pngimage/png
.gifimage/gif
.jpgimage/jpg
.jpegimage/jpeg
.bmpimage/bmp
Audio.mp3audio/mp3
.wavaudio/wav
.oggaudio/x-ogg
.midaudio/mid
.midiaudio/midi
.amraudio/AMR
Video.mpegvideo/mpeg
.3gpvideo/3gpp
Package.jarapplication/java-archive
.zipapplication/zip
.rarapplication/x-rar-compressed
.gzapplication/gzip

For more info on MIME types and files handling based on their extension take a look at the MIMETypeMap documentation.

2012年7月12日 星期四

MIME types

MIME types

MIME is a standard that classifies resources and provides information (to programs) about how to handle them. This allows the correct handling and interpretation of different type files by programs (like browsers). For example, thanks to MIME, browsers can open correctly a ".txt" file as a plain text resource and not as a video stream or other type.
When a MIME type is not specified for a resource, the handling program can "guess" it from the resource's extension (e.g., a file with the ".bmp" extension is supposed to contain a bitmap image). But this may not always give good results as a file extension may be asociated to more than one format. On the other hand, MIME types are unique. This is the main reason why MIME types should be defined everywhere possible.
In HTML documents, authors can use MIME types in many instances, usually through the "type" attribute. Some special cases of its use are with the "enctype" attribute in the HTML form element, and when defining the document's "content-type" in the HTML meta tag.

MIME types list

MIME typeExtension
application/acad.dwg
application/arj.arj
application/base64.mm
application/base64.mme
application/binhex.hqx
application/binhex4.hqx
application/book.boo
application/book.book
application/cdf.cdf
application/clariscad.ccad
application/commonground.dp
application/drafting.drw
application/dsptype.tsp
application/dxf.dxf
application/envoy.evy
application/excel.xl
application/excel.xla
application/excel.xlb
application/excel.xlc
application/excel.xld
application/excel.xlk
application/excel.xll
application/excel.xlm
application/excel.xls
application/excel.xlt
application/excel.xlv
application/excel.xlw
application/fractals.fif
application/freeloader.frl
application/futuresplash.spl
application/gnutar.tgz
application/groupwise.vew
application/hlp.hlp
application/hta.hta
application/i-deas.unv
application/iges.iges
application/iges.igs
application/inf.inf
application/java.clas
application/java-byte-code.clas
application/lha.lha
application/lzx.lzx
application/mac-binary.bin
application/mac-binhex.hqx
application/mac-binhex40.hqx
application/mac-compactpro.cpt
application/macbinary.bin
application/marc.mrc
application/mbedlet.mbd
application/mcad.mcd
application/mime.aps
application/mspowerpoint.pot
application/mspowerpoint.pps
application/mspowerpoint.ppt
application/mspowerpoint.ppz
application/msword.doc
application/msword.dot
application/msword.w6w
application/msword.wiz
application/msword.word
application/mswrite.wri
application/netmc.mcp
application/octet-stream.a
application/octet-stream.arc
application/octet-stream.arj
application/octet-stream.bin
application/octet-stream.com
application/octet-stream.dump
application/octet-stream.exe
application/octet-stream.lha
application/octet-stream.lhx
application/octet-stream.lzh
application/octet-stream.lzx
application/octet-stream.o
application/octet-stream.psd
application/octet-stream.save
application/octet-stream.uu
application/octet-stream.zoo
application/oda.oda
application/pdf.pdf
application/pkcs-12.p12
application/pkcs-crl.crl
application/pkcs10.p10
application/pkcs7-mime.p7c
application/pkcs7-mime.p7m
application/pkcs7-signature.p7s
application/pkix-cert.cer
application/pkix-cert.crt
application/pkix-crl.crl
application/plain.text
application/postscript.ai
application/postscript.eps
application/postscript.ps
application/powerpoint.ppt
application/pro_eng.part
application/pro_eng.prt
application/ringing-tones.rng
application/rtf.rtf
application/rtf.rtx
application/sdp.sdp
application/sea.sea
application/set.set
application/sla.stl
application/smil.smi
application/smil.smil
application/solids.sol
application/sounder.sdr
application/step.step
application/step.stp
application/streamingmedia.ssm
application/toolbook.tbk
application/vda.vda
application/vnd.fdf.fdf
application/vnd.hp-hpgl.hgl
application/vnd.hp-hpgl.hpg
application/vnd.hp-hpgl.hpgl
application/vnd.hp-pcl.pcl
application/vnd.ms-excel.xlb
application/vnd.ms-excel.xlc
application/vnd.ms-excel.xll
application/vnd.ms-excel.xlm
application/vnd.ms-excel.xls
application/vnd.ms-excel.xlw
application/vnd.ms-pki.certstore.sst
application/vnd.ms-pki.pko.pko
application/vnd.ms-pki.seccat.cat
application/vnd.ms-pki.stl.stl
application/vnd.ms-powerpoint.pot
application/vnd.ms-powerpoint.ppa
application/vnd.ms-powerpoint.pps
application/vnd.ms-powerpoint.ppt
application/vnd.ms-powerpoint.pwz
application/vnd.ms-project.mpp
application/vnd.nokia.configuration-message.ncm
application/vnd.nokia.ringing-tone.rng
application/vnd.rn-realmedia.rm
application/vnd.rn-realplayer.rnx
application/vnd.wap.wmlc.wmlc
application/vnd.wap.wmlscriptc.wmls
application/vnd.xara.web
application/vocaltec-media-desc.vmd
application/vocaltec-media-file.vmf
application/wordperfect.wp
application/wordperfect.wp5
application/wordperfect.wp6
application/wordperfect.wpd
application/wordperfect6.0.w60
application/wordperfect6.0.wp5
application/wordperfect6.1.w61
application/x-123.wk1
application/x-aim.aim
application/x-authorware-bin.aab
application/x-authorware-map.aam
application/x-authorware-seg.aas
application/x-bcpio.bcpi
application/x-binary.bin
application/x-binhex40.hqx
application/x-bsh.bsh
application/x-bsh.sh
application/x-bsh.shar
application/x-bytecode.elisp.elc
application/x-bytecode.python.pyc
application/x-bzip.bz
application/x-bzip2.boz
application/x-bzip2.bz2
application/x-cdf.cdf
application/x-cdlink.vcd
application/x-chat.cha
application/x-chat.chat
application/x-cmu-raster.ras
application/x-cocoa.cco
application/x-compactpro.cpt
application/x-compress.z
application/x-compressed.gz
application/x-compressed.tgz
application/x-compressed.z
application/x-compressed.zip
application/x-conference.nsc
application/x-cpio.cpio
application/x-cpt.cpt
application/x-csh.csh
application/x-deepv.deep
application/x-director.dcr
application/x-director.dir
application/x-director.dxr
application/x-dvi.dvi
application/x-elc.elc
application/x-envoy.env
application/x-envoy.evy
application/x-esrehber.es
application/x-excel.xla
application/x-excel.xlb
application/x-excel.xlc
application/x-excel.xld
application/x-excel.xlk
application/x-excel.xll
application/x-excel.xlm
application/x-excel.xls
application/x-excel.xlt
application/x-excel.xlv
application/x-excel.xlw
application/x-frame.mif
application/x-freelance.pre
application/x-gsp.gsp
application/x-gss.gss
application/x-gtar.gtar
application/x-gzip.gz
application/x-gzip.gzip
application/x-hdf.hdf
application/x-helpfile.help
application/x-helpfile.hlp
application/x-httpd-imap.imap
application/x-ima.ima
application/x-internett-signup.ins
application/x-inventor.iv
application/x-ip2.ip
application/x-java-class.clas
application/x-java-commerce.jcm
application/x-javascript.js
application/x-koan.skd
application/x-koan.skm
application/x-koan.skp
application/x-koan.skt
application/x-ksh.ksh
application/x-latex.late
application/x-latex.ltx
application/x-lha.lha
application/x-lisp.lsp
application/x-livescreen.ivy
application/x-lotus.wq1
application/x-lotusscreencam.scm
application/x-lzh.lzh
application/x-lzx.lzx
application/x-mac-binhex40.hqx
application/x-macbinary.bin
application/x-magic-cap-package-1.0.mc$
application/x-mathcad.mcd
application/x-meme.mm
application/x-midi.mid
application/x-midi.midi
application/x-mif.mif
application/x-mix-transfer.nix
application/x-mplayer2.asx
application/x-msexcel.xla
application/x-msexcel.xls
application/x-msexcel.xlw
application/x-mspowerpoint.ppt
application/x-navi-animation.ani
application/x-navidoc.nvd
application/x-navimap.map
application/x-navistyle.stl
application/x-netcdf.cdf
application/x-netcdf.nc
application/x-newton-compatible-pkg.pkg
application/x-nokia-9000-communicator-add-on-softw.aos
application/x-omc.omc
application/x-omcdatamaker.omcd
application/x-omcregerator.omcr
application/x-pagemaker.pm4
application/x-pagemaker.pm5
application/x-pcl.pcl
application/x-pixclscript.plx
application/x-pkcs10.p10
application/x-pkcs12.p12
application/x-pkcs7-certificates.spc
application/x-pkcs7-certreqresp.p7r
application/x-pkcs7-mime.p7c
application/x-pkcs7-mime.p7m
application/x-pkcs7-signature.p7a
application/x-pointplus.css
application/x-portable-anymap.pnm
application/x-project.mpc
application/x-project.mpt
application/x-project.mpv
application/x-project.mpx
application/x-qpro.wb1
application/x-rtf.rtf
application/x-sdp.sdp
application/x-sea.sea
application/x-seelogo.sl
application/x-sh.sh
application/x-shar.sh
application/x-shar.shar
application/x-shockwave-flash.swf
application/x-sit.sit
application/x-sprite.spr
application/x-sprite.spri
application/x-stuffit.sit
application/x-sv4cpio.sv4c
application/x-sv4crc.sv4c
application/x-tar.tar
application/x-tbook.sbk
application/x-tbook.tbk
application/x-tcl.tcl
application/x-tex.tex
application/x-texinfo.texi
application/x-troff.roff
application/x-troff.t
application/x-troff.tr
application/x-troff-man.man
application/x-troff-me.me
application/x-troff-ms.ms
application/x-troff-msvideo.avi
application/x-ustar.usta
application/x-visio.vsd
application/x-visio.vst
application/x-visio.vsw
application/x-vnd.audioexplosion.mzz.mzz
application/x-vnd.ls-xpix.xpix
application/x-vrml.vrml
application/x-wais-source.src
application/x-wais-source.wsrc
application/x-winhelp.hlp
application/x-wintalk.wtk
application/x-world.svr
application/x-world.wrl
application/x-wpwin.wpd
application/x-wri.wri
application/x-x509-ca-cert.cer
application/x-x509-ca-cert.crt
application/x-x509-ca-cert.der
application/x-x509-user-cert.crt
application/x-zip-compressed.zip
application/xml.xml
application/zip.zip
audio/aiff.aif
audio/aiff.aifc
audio/aiff.aiff
audio/basic.au
audio/basic.snd
audio/it.it
audio/make.funk
audio/make.my
audio/make.pfun
audio/make.my.funk.pfun
audio/mid.rmi
audio/midi.kar
audio/midi.mid
audio/midi.midi
audio/mod.mod
audio/mpeg.m2a
audio/mpeg.mp2
audio/mpeg.mpa
audio/mpeg.mpg
audio/mpeg.mpga
audio/mpeg3.mp3
audio/nspaudio.la
audio/nspaudio.lma
audio/s3m.s3m
audio/tsp-audio.tsi
audio/tsplayer.tsp
audio/vnd.qcelp.qcp
audio/voc.voc
audio/voxware.vox
audio/wav.wav
audio/x-adpcm.snd
audio/x-aiff.aif
audio/x-aiff.aifc
audio/x-aiff.aiff
audio/x-au.au
audio/x-gsm.gsd
audio/x-gsm.gsm
audio/x-jam.jam
audio/x-liveaudio.lam
audio/x-mid.mid
audio/x-mid.midi
audio/x-midi.mid
audio/x-midi.midi
audio/x-mod.mod
audio/x-mpeg.mp2
audio/x-mpeg-3.mp3
audio/x-mpequrl.m3u
audio/x-nspaudio.la
audio/x-nspaudio.lma
audio/x-pn-realaudio.ra
audio/x-pn-realaudio.ram
audio/x-pn-realaudio.rm
audio/x-pn-realaudio.rmm
audio/x-pn-realaudio.rmp
audio/x-pn-realaudio-plugin.ra
audio/x-pn-realaudio-plugin.rmp
audio/x-pn-realaudio-plugin.rpm
audio/x-psid.sid
audio/x-realaudio.ra
audio/x-twinvq.vqf
audio/x-twinvq-plugin.vqe
audio/x-twinvq-plugin.vql
audio/x-vnd.audioexplosion.mjuicemediafile.mjf
audio/x-voc.voc
audio/x-wav.wav
audio/xm.xm
chemical/x-pdb.pdb
chemical/x-pdb.xyz
drawing/x-dwf.dwf
i-world/i-vrml.ivr
image/bmp.bm
image/bmp.bmp
image/cmu-raster.ras
image/cmu-raster.rast
image/fif.fif
image/florian.flo
image/florian.turb
image/g3fax.g3
image/gif.gif
image/ief.ief
image/ief.iefs
image/jpeg.jfif
image/jpeg.jpe
image/jpeg.jpeg
image/jpeg.jpg
image/jutvision.jut
image/naplps.nap
image/naplps.napl
image/pict.pic
image/pict.pict
image/pjpeg.jfif
image/pjpeg.jpe
image/pjpeg.jpeg
image/pjpeg.jpg
image/png.png
image/png.x-pn
image/tiff.tif
image/tiff.tiff
image/vasa.mcf
image/vnd.dwg.dwg
image/vnd.dwg.dxf
image/vnd.dwg.svf
image/vnd.fpx.fpx
image/vnd.net-fpx.fpx
image/vnd.rn-realflash.rf
image/vnd.rn-realpix.rp
image/vnd.wap.wbmp.wbmp
image/vnd.xiff.xif
image/x-cmu-raster.ras
image/x-dwg.dwg
image/x-dwg.dxf
image/x-dwg.svf
image/x-icon.ico
image/x-jg.art
image/x-jps.jps
image/x-niff.nif
image/x-niff.niff
image/x-pcx.pcx
image/x-pict.pct
image/x-portable-anymap.pnm
image/x-portable-bitmap.pbm
image/x-portable-graymap.pgm
image/x-portable-greymap.pgm
image/x-portable-pixmap.ppm
image/x-quicktime.qif
image/x-quicktime.qti
image/x-quicktime.qtif
image/x-rgb.rgb
image/x-tiff.tif
image/x-tiff.tiff
image/x-windows-bmp.bmp
image/x-xbitmap.xbm
image/x-xbm.xbm
image/x-xpixmap.pm
image/x-xpixmap.xpm
image/x-xwd.xwd
image/x-xwindowdump.xwd
image/xbm.xbm
image/xpm.xpm
message/rfc822.mht
message/rfc822.mhtm
message/rfc822.mime
model/iges.iges
model/iges.igs
model/vnd.dwf.dwf
model/vrml.vrml
model/vrml.wrl
model/vrml.wrz
model/x-pov.pov
multipart/x-gzip.gzip
multipart/x-ustar.usta
multipart/x-zip.zip
music/crescendo.mid
music/crescendo.midi
music/x-karaoke.kar
paleovu/x-pv.pvu
text/asp.asp
text/css.css
text/html.acgi
text/html.htm
text/html.html
text/html.htx
text/html.shtm
text/mcf.mcf
text/pascal.pas
text/plain.c
text/plain.c++
text/plain.cc
text/plain.com
text/plain.conf
text/plain.cxx
text/plain.def
text/plain.f
text/plain.f90
text/plain.for
text/plain.g
text/plain.h
text/plain.hh
text/plain.idc
text/plain.jav
text/plain.java
text/plain.list
text/plain.log
text/plain.lst
text/plain.m
text/plain.mar
text/plain.pl
text/plain.sdml
text/plain.text
text/plain.txt
text/richtext.rt
text/richtext.rtf
text/richtext.rtx
text/scriplet.wsc
text/sgml.sgm
text/sgml.sgml
text/tab-separated-values.tsv
text/uri-list.uni
text/uri-list.unis
text/uri-list.uri
text/uri-list.uris
text/vnd.abc.abc
text/vnd.fmi.flexstor.flx
text/vnd.rn-realtext.rt
text/vnd.wap.wml.wml
text/vnd.wap.wmlscript.wmls
text/webviewhtml.htt
text/x-asm.asm
text/x-asm.s
text/x-audiosoft-intra.aip
text/x-c.c
text/x-c.cc
text/x-c.cpp
text/x-component.htc
text/x-fortran.f
text/x-fortran.f77
text/x-fortran.f90
text/x-fortran.for
text/x-h.h
text/x-h.hh
text/x-java-source.jav
text/x-java-source.java
text/x-la-asf.lsx
text/x-m.m
text/x-pascal.p
text/x-script.hlb
text/x-script.csh.csh
text/x-script.elisp.el
text/x-script.guile.scm
text/x-script.ksh.ksh
text/x-script.lisp.lsp
text/x-script.perl.pl
text/x-script.perl-module.pm
text/x-script.phyton.py
text/x-script.rexx.rexx
text/x-script.scheme.scm
text/x-script.sh.sh
text/x-script.tcl.tcl
text/x-script.tcsh.tcsh
text/x-script.zsh.zsh
text/x-server-parsed-html.shtm
text/x-server-parsed-html.ssi
text/x-setext.etx
text/x-sgml.sgm
text/x-sgml.sgml
text/x-speech.spc
text/x-speech.talk
text/x-uil.uil
text/x-uuencode.uu
text/x-uuencode.uue
text/x-vcalendar.vcs
text/xml.xml
video/animaflex.afl
video/avi.avi
video/avs-video.avs
video/dl.dl
video/fli.fli
video/gl.gl
video/mpeg.m1v
video/mpeg.m2v
video/mpeg.mp2
video/mpeg.mp3
video/mpeg.mpa
video/mpeg.mpe
video/mpeg.mpeg
video/mpeg.mpg
video/msvideo.avi
video/quicktime.moov
video/quicktime.mov
video/quicktime.qt
video/vdo.vdo
video/vivo.viv
video/vivo.vivo
video/vnd.rn-realvideo.rv
video/vnd.vivo.viv
video/vnd.vivo.vivo
video/vosaic.vos
video/x-amt-demorun.xdr
video/x-amt-showrun.xsr
video/x-atomic3d-feature.fmf
video/x-dl.dl
video/x-dv.dif
video/x-dv.dv
video/x-fli.fli
video/x-gl.gl
video/x-isvideo.isu
video/x-motion-jpeg.mjpg
video/x-mpeg.mp2
video/x-mpeg.mp3
video/x-mpeq2a.mp2
video/x-ms-asf.asf
video/x-ms-asf.asx
video/x-ms-asf-plugin.asx
video/x-msvideo.avi
video/x-qtc.qtc
video/x-scm.scm
video/x-sgi-movie.movi
video/x-sgi-movie.mv
windows/metafile.wmf
www/mime.mime
x-conference/x-cooltalk.ice
x-music/x-midi.mid
x-music/x-midi.midi
x-world/x-3dmf.3dm
x-world/x-3dmf.3dmf
x-world/x-3dmf.qd3
x-world/x-3dmf.qd3d
x-world/x-svr.svr
x-world/x-vrml.vrml
x-world/x-vrml.wrl
x-world/x-vrml.wrz
x-world/x-vrt.vrt
xgl/drawing.xgz
xgl/movie.xmz