Android(安卓)Intent用法详解

如果是从BroadcastReceiver 启动一个新的Activity , 不要忘记i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);public class MyReceiver extends BroadcastReceiver{public static final String action=”acc”;public void onReceive(Context context, Intent intent) {Intent i=new Intent(context,Receivered.class);i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(i);}}1. 指定act ion 和type// SIM importIntent importIntent = new Intent(Intent.ACTION_VIEW);importIntent.setType(“vnd.android.cursor.item/sim-contact”);importIntent.setClassName(“com.android.phone”, “com.android.phone.SimContacts”);menu.add(0, 0, 0, R.string.importFromSim).setIcon(R.drawable.ic_menu_import_contact).setIntent(importIntent);2. 指定act ion, da ta和type(1)隐式查找type示例代码:uri: content://simcontacts/simPeople/(id)intent = new Intent(“android.intent.action.SIMEDIT”,uri);startActivity(intent);程序会很据data中的uri去查找匹配的type(必须的)provider中的getType()case SIM_PEOPLE_ID:return “vnd.android.cursor.item/sim-contact”;配置文件中的filter设定AndroidManifest.xml也可以自己设定type,但只能使用 setDataAndType()3. 其他设定intent的属性方式Intent setComponent(ComponentName component)Intent setClassName(Context packageContext, String className)Intent setClassName(String packageName, String className)Intent setClass(Context packageContext, Class cls)打开其他APK文件的ACTIVITYIntent mIntent = new Intent();ComponentName comp = new ComponentName(“com.android.a”,”com.android.a.AbcActivity” );mIntent.setComponent(comp);mIntent.setAction(“android.intent.action.MAIN”);startActivity(mIntent);显示网页:1. Uri uri = Uri.parse(“http://www.google.com”);2. Intent it = new Intent(Intent.ACTION_VIEW,uri);3. startActivity(it);显示地图:1. Uri uri = Uri.parse(“geo:38.899533,-77.036476″);2. Intent it = new Intent(Intent.Action_VIEW,uri);3. startActivity(it);路径规划:1. Uri uri = Uri.parse(“http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en”);2. Intent it = new Intent(Intent.ACTION_VIEW,URI);3. startActivity(it);拨打电话:调用拨号程序1. Uri uri = Uri.parse(“tel:xxxxxx”);2. Intent it = new Intent(Intent.ACTION_DIAL, uri);3. startActivity(it);1. Uri uri = Uri.parse(“tel.xxxxxx”);2. Intent it =new Intent(Intent.ACTION_CALL,uri);3. 要使用这个必须在配置文件中加入发送SMS/MMS调用发送短信的程序1. Intent it = new Intent(Intent.ACTION_VIEW);2. it.putExtra(“sms_body”, “The SMS text”);3. it.setType(“vnd.android-dir/mms-sms”);4. startActivity(it);发送短信1. Uri uri = Uri.parse(“smsto:0800000123″);2. Intent it = new Intent(Intent.ACTION_SENDTO, uri);3. it.putExtra(“sms_body”, “The SMS text”);4. startActivity(it);发送彩信1. Uri uri = Uri.parse(“content://media/external/images/media/23″);2. Intent it = new Intent(Intent.ACTION_SEND);3. it.putExtra(“sms_body”, “some text”);4. it.putExtra(Intent.EXTRA_STREAM, uri);5. it.setType(“image/png”);6. startActivity(it);发送Email1.2. Uri uri = Uri.parse(“mailto:xxx@abc.com”);3. Intent it = new Intent(Intent.ACTION_SENDTO, uri);4. startActivity(it);1. Intent it = new Intent(Intent.ACTION_SEND);2. it.putExtra(Intent.EXTRA_EMAIL, “me@abc.com”);3. it.putExtra(Intent.EXTRA_TEXT, “The email body text”);4. it.setType(“text/plain”);5. startActivity(Intent.createChooser(it, “Choose Email Client”));1. Intent it=new Intent(Intent.ACTION_SEND);2. String[] tos={“me@abc.com”};3. String[] ccs={“you@abc.com”};4. it.putExtra(Intent.EXTRA_EMAIL, tos);5. it.putExtra(Intent.EXTRA_CC, ccs);6. it.putExtra(Intent.EXTRA_TEXT, “The email body text”);7. it.putExtra(Intent.EXTRA_SUBJECT, “The email subject text”);8. it.setType(“message/rfc822″);9. startActivity(Intent.createChooser(it, “Choose Email Client”));添加附件1. Intent it = new Intent(Intent.ACTION_SEND);2. it.putExtra(Intent.EXTRA_SUBJECT, “The email subject text”);3. it.putExtra(Intent.EXTRA_STREAM, “file:///sdcard/mysong.mp3″);4. sendIntent.setType(“audio/mp3″);5. startActivity(Intent.createChooser(it, “Choose Email Client”));播放多媒体//方法1.Uri uri = Uri.parse(“file:///sdcard/song.mp3″);Intent it = new Intent(Intent.ACTION_VIEW, uri);// it.addFlags(it.FLAG_ACTIVITY_NEW_TASK);//非必须选项it.setDataAndType(uri, “audio/mp3″);context.startActivity(it);//方法2.1.2. Intent it = new Intent(Intent.ACTION_VIEW);3. Uri uri = Uri.parse(“file:///sdcard/song.mp3″);4. it.setDataAndType(uri, “audio/mp3″);5. startActivity(it);//方法3. 启动一个播放器并播放一个系统声音1. Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, “1″);2. Intent it = new Intent(Intent.ACTION_VIEW, uri);3. startActivity(it);Uninstall 程序1. Uri uri = Uri.fromParts(“package”, strPackageName, null);2. Intent it = new Intent(Intent.ACTION_DELETE, uri);3. startActivity(it);uninstall apk1. Uri uninstallUri = Uri.fromParts(“package”, “xxx”, null);2.3. returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri);install apk1. Uri installUri = Uri.fromParts(“package”, “xxx”, null);2.3. returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);play audio1. Uri playUri = Uri.parse(“file:///sdcard/download/everything.mp3″);2.3. returnIt = new Intent(Intent.ACTION_VIEW, playUri);哈,原来你还没贴完,我再加个:1. //发送附件2. Intent it = new Intent(Intent.ACTION_SEND);3. it.putExtra(Intent.EXTRA_SUBJECT, “The email subject text”);4. it.putExtra(Intent.EXTRA_STREAM, “file:///sdcard/eoe.mp3″);5. sendIntent.setType(“audio/mp3″);6. startActivity(Intent.createChooser(it, “Choose Email Client”));market相关market相关再来一个market相关的:market相关1. //搜索应用2. Uri uri = Uri.parse(“market://search?q=pname:pkg_name”);3. Intent it = new Intent(Intent.ACTION_VIEW, uri);4. startActivity(it);5. //where pkg_name is the full package path for an application7. //显示指定应用的详细页面(这个好像不支持了,找不到app_id)8. Uri uri = Uri.parse(“market://details?id=app_id”);9. Intent it = new Intent(Intent.ACTION_VIEW, uri);10. startActivity(it);Uninstall 应用程序1. Uri uri = Uri.fromParts(“package”, strPackageName, null);2. Intent it = new Intent(Intent.ACTION_DELETE, uri);3. startActivity(it);
1、调用其自带的播放器:[java]    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/Test_Movie.m4v");         //调用系统自带的播放器             Intent intent = new Intent(Intent.ACTION_VIEW);            Log.v("URI:::::::::", uri.toString());            intent.setDataAndType(uri, "video/mp4");            startActivity(intent);    2、使用VideoView来实现:[java]    Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()+"/Test_Movie.m4v");        VideoView videoView = (VideoView)this.findViewById(R.id.video_view);        videoView.setMediaController(new MediaController(this));        videoView.setVideoURI(uri);        videoView.start();        videoView.requestFocus();    3、使用MediaPlayer:[java]    package demo.camera;        import java.io.IOException;        import Android.app.Activity;        import Android.media.MediaPlayer;        import Android.media.MediaPlayer.OnCompletionListener;        import Android.media.MediaPlayer.OnErrorListener;        import Android.media.MediaPlayer.OnInfoListener;        import Android.media.MediaPlayer.OnPreparedListener;        import Android.media.MediaPlayer.OnSeekCompleteListener;        import Android.media.MediaPlayer.OnVideoSizeChangedListener;        import Android.os.Bundle;        import Android.os.Environment;        import Android.util.Log;        import Android.view.Display;        import Android.view.SurfaceHolder;        import Android.view.SurfaceView;        import Android.widget.LinearLayout;        /**       * 该实例中使用MediaPlayer完成播放,同时界面使用SurfaceView来实现       *        * 这里我们实现MediaPlayer中很多状态变化时的监听器       *        * 使用Mediaplayer时,也可以使用MediaController类,但是需要实现MediaController.mediaController接口       * 实现一些控制方法。       *        * 然后,设置controller.setMediaPlayer(),setAnchorView(),setEnabled(),show()就可以了,这里不再实现       * @author Administrator       *       */        public class VideoSurfaceDemo extends Activity implements OnCompletionListener,OnErrorListener,OnInfoListener,            OnPreparedListener, OnSeekCompleteListener,OnVideoSizeChangedListener,SurfaceHolder.Callback{            private Display currDisplay;            private SurfaceView surfaceView;            private SurfaceHolder holder;            private MediaPlayer player;            private int vWidth,vHeight;            //private boolean readyToPlay = false;                             public void onCreate(Bundle savedInstanceState){                super.onCreate(savedInstanceState);                this.setContentView(R.layout.video_surface);                                        surfaceView = (SurfaceView)this.findViewById(R.id.video_surface);                //给SurfaceView添加CallBack监听                 holder = surfaceView.getHolder();                holder.addCallback(this);                //为了可以播放视频或者使用Camera预览,我们需要指定其Buffer类型                 holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);                                //下面开始实例化MediaPlayer对象                 player = new MediaPlayer();                player.setOnCompletionListener(this);                player.setOnErrorListener(this);                player.setOnInfoListener(this);                player.setOnPreparedListener(this);                player.setOnSeekCompleteListener(this);                player.setOnVideoSizeChangedListener(this);                Log.v("Begin:::", "surfaceDestroyed called");                //然后指定需要播放文件的路径,初始化MediaPlayer                 String dataPath = Environment.getExternalStorageDirectory().getPath()+"/Test_Movie.m4v";                try {                    player.setDataSource(dataPath);                    Log.v("Next:::", "surfaceDestroyed called");                } catch (IllegalArgumentException e) {                    e.printStackTrace();                } catch (IllegalStateException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }                //然后,我们取得当前Display对象                 currDisplay = this.getWindowManager().getDefaultDisplay();            }                        @Override            public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {                // 当Surface尺寸等参数改变时触发                 Log.v("Surface Change:::", "surfaceChanged called");            }            @Override            public void surfaceCreated(SurfaceHolder holder) {                // 当SurfaceView中的Surface被创建的时候被调用                 //在这里我们指定MediaPlayer在当前的Surface中进行播放                 player.setDisplay(holder);                //在指定了MediaPlayer播放的容器后,我们就可以使用prepare或者prepareAsync来准备播放了                 player.prepareAsync();                            }            @Override            public void surfaceDestroyed(SurfaceHolder holder) {                                Log.v("Surface Destory:::", "surfaceDestroyed called");            }            @Override            public void onVideoSizeChanged(MediaPlayer arg0, int arg1, int arg2) {                // 当video大小改变时触发                 //这个方法在设置player的source后至少触发一次                 Log.v("Video Size Change", "onVideoSizeChanged called");                            }            @Override            public void onSeekComplete(MediaPlayer arg0) {                // seek操作完成时触发                 Log.v("Seek Completion", "onSeekComplete called");                            }            @Override            public void onPrepared(MediaPlayer player) {                // 当prepare完成后,该方法触发,在这里我们播放视频                                 //首先取得video的宽和高                 vWidth = player.getVideoWidth();                vHeight = player.getVideoHeight();                                if(vWidth > currDisplay.getWidth() || vHeight > currDisplay.getHeight()){                    //如果video的宽或者高超出了当前屏幕的大小,则要进行缩放                     float wRatio = (float)vWidth/(float)currDisplay.getWidth();                    float hRatio = (float)vHeight/(float)currDisplay.getHeight();                                        //选择大的一个进行缩放                     float ratio = Math.max(wRatio, hRatio);                                        vWidth = (int)Math.ceil((float)vWidth/ratio);                    vHeight = (int)Math.ceil((float)vHeight/ratio);                                        //设置surfaceView的布局参数                     surfaceView.setLayoutParams(new LinearLayout.LayoutParams(vWidth, vHeight));                                        //然后开始播放视频                                         player.start();                }            }            @Override            public boolean onInfo(MediaPlayer player, int whatInfo, int extra) {                // 当一些特定信息出现或者警告时触发                 switch(whatInfo){                case MediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:                    break;                case MediaPlayer.MEDIA_INFO_METADATA_UPDATE:                      break;                case MediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:                    break;                case MediaPlayer.MEDIA_INFO_NOT_SEEKABLE:                     break;                }                return false;            }            @Override            public boolean onError(MediaPlayer player, int whatError, int extra) {                Log.v("Play Error:::", "onError called");                switch (whatError) {                case MediaPlayer.MEDIA_ERROR_SERVER_DIED:                    Log.v("Play Error:::", "MEDIA_ERROR_SERVER_DIED");                    break;                case MediaPlayer.MEDIA_ERROR_UNKNOWN:                    Log.v("Play Error:::", "MEDIA_ERROR_UNKNOWN");                    break;                default:                    break;                }                return false;            }            @Override            public void onCompletion(MediaPlayer player) {                // 当MediaPlayer播放完成后触发                 Log.v("Play Over:::", "onComletion called");                this.finish();            }        }