1.强制执行单任务模式:html
确保设备上只有一个activity实例在运行,须要在activity元素中包含MAIN和LAUNCHER两个intent过滤器:java
android:launchMode="singleInstance"android
2.将全部的activity做为同一个任务,共享信息方便:git
android:launchMode="singleTask"app
3.不管用户经过什么方式进入activity都能保存任务的状态:(确保用户老是可以返回到关闭以前的状态)less
android:alwaysRetainTaskState="true"ide
4.activity强制设置纵向模式:函数
android:screenOrientation="portrait"ui
5.activity强制设置横向模式:this
android:screenOrientation="landscape"
6.防止硬键盘滑出:
android:configChanges="orientation|keyboardHidden" 能够和screenOrientation一块儿使用
使用Context.this代替this
使用getApplicationContext()来代替this
显示的使用类名
声明方法
onClick方法中:
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say a word or phrase\nand it will show as text"); startActivityForResult(intent, RECOGNIZER_EXAMPLE); onActivityResult(): if(requestCode == RECOGNIZER_EXAMPLE && resultCode == RESULT_OK){ ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS); }
在Activity调用另外一Activity时,一般使用以下方法得到返回值:
Intent sampleIntent = new Intent(ThisActivity.this, NewActivity.class); startActivityForResult(sampleIntent , 1);
但若是调用的是Dialog类,或其余非Activity类时,没法使用startActivityForResult()方法。
此时,需使用另外一种方法得到返回值。方法以下:
假设:主Activity为MainActivity;被调用的Dialog类为SampleDialog
1.咱们需定义一个接口类:
interface MyListener{ public void refreshActivity(String text); }
2.在SampleDIalog的构造函数中传入MyListener:
public MyListener (MyListener myListener){ this.mMyListener = myListener; }
3.在须要返回的地方调用refreshActivity()方法:
mMyListener.refreshActivity();
4.在MainActivity中实现MyListener接口,并在show Dialog时传入实现的myListener:
private MyListener myListener = new MyListener(){ @Override public void refreshActivity(String text){ this.mTextView1.setText(text); } }; new SampleDialog(myListener).show;
这样便能从Dialog返回须要的数据。
根据我的经验大概总结三种方式:(由A向B传递参数)
1.intent传递消息
A中添加数据:
Intent intent = new Intent(A.this, B.class); intent.putExtra("activityMain","数据来自A"); // A中把数据添加进去 startActivity(); //startActivityForResult(intent1,REQUEST_CODE);
B中接收数据
Bundle extras = getIntent().getExtras(); if(extras!=null) String MUSIC_PATH =extras.getString("activityMain");
在基类的Activity中封装方法:
<> (String key) { Intent intent = .getIntent()Object obj = intent.getExtras().get(key)(obj == ) { } () obj} (String key) { .getIntent().hasExtra(key)}
2.使用广播方式,server传递消息这个方式也与intent有关
优势:能够后台运行,直到真正退出应用程序
发送端:
ActivityReceiver activityreceiver = new ActivityReceiver();//建立广播接收派生类 I IntentFilter filter = new IntentFilter();//建立IntentFilter消息过滤器 filter.addAction("jjplayer.update");//添加消息行为 registerReceiver(activityreceiver, filter);//注册监听 Intent intent = new Intent(this,MyService.class); startService(intent);
其中ActivityReceiver 是本身建立的接收广播类,参考代码以下:
public class ActivityReceiver extends BroadcastReceiver { //自定义的广播接收者 @Override public void onReceive(Context context, Intent intent) { method stub int update =intent.getIntExtra("update",-1);//获得Intent中的数据 switch(update){ case 1://没有声音播放,设置当前状态 status =1; break; case 2://开始播放,设置当前图片为播放状态 //start.setImageResource(R.drawable.temp); btStart.setImageResource(R.drawable.pause); status = 2; break; case 3://暂停当中,设置图片和状态 btStart.setImageResource(R.drawable.play); status = 3; break; } } }
发送端注册以后,就能够根据不一样的响应机制发送消息了,好比监听按键来发送消息,参考代码以下:
public void onClick(View v) { //来自单击鼠标接口onclickListenner的方法 Intent intent = new Intent("yxj.play.control");//建立intent,滤波器内容为 //包yxj.play中的control类 switch(v.getId()){ case R.id.btStart://开始播放按钮 intent.putExtra("ACTION", 1); //存放数据 sendBroadcast(intent); //发送数据 break; case R.id.btStop: intent.putExtra("ACTION", 2); sendBroadcast(intent); break; } }
接收端:
接收端注册信息
ServiceReceiver serviceRt = new ServiceReceiver();//建立广播类BroadcastReceiver IntentFilter intentfilter = new IntentFilter();//建立过滤器 intentfilter.addAction("yxj.play.control"); registerReceiver(serviceRt, intentfilter);//注册其中ServiceReceiver 是接收server消息的处理类,参考代码以下 public class ServiceReceiver extends BroadcastReceiver{ Uri uri = Uri.parse("file:///sdcard/breathhard.mp3"); @Override public void onReceive(Context context, Intent intent) { int action = intent.getIntExtra("ACTION",-1);//获取action switch(action){//根据action作出响应 case 1: if(status==1){ mp = MediaPlayer.create(context, uri); status = 2; Intent sendIntent = new Intent("yxj.play.update"); sendIntent.putExtra("update", 2);//准备发送小消息的内容 sendBroadcast(sendIntent);//广播方式发送消息 mp.start(); }
server注册:
这种方式的server须要在Androidmanifest.xml文件下面注册,在</application>以前添加
<service android:name = ".MyService" android:process = ":remote"> </service>
3.使用SharedPreferrences存储类
在类A中设置:
SharedPreferences param = getSharedPreferences("JJParam", MODE_PRIVATE); SharedPreferences.Editor editor = param.edit(); editor.putString("MUSIC_PATH", currentDirectory.toString()); editor.commit();
在类B中接收
SharedPreferences param = getSharedPreferences("JJParam", MODE_PRIVATE); if(param != null) {//若是文件已经存在,则继续 if(param.getString("MUSIC_PATH",null)!=null)//获取文件路径 Music_Path = param.getString("MUSIC_PATH",null);
这种用法比较简单,生成的JJParam.xml文件系统自动存储到了/data/data/PACKAGE_NAME/shared_prefs目录下
/data/data/PACKAGE_NAME /shared_prefs 目录下。
4. URI
Uri分红三部份:访问资源的命名机制;存放资源的主机名;资源自身的名称,由路径表示。
好比“Http://www.baidu.com/text/xxx.html”
这里面Http是命名机制(协议名),
www.baidu.com是资源位置,text/xxxlhtml是资源名称。
在Android系统中如“content://contacts/1”表示,
在系统中contacts(联系人)中的第1号,就很容易定位到一个资源了,
采用了这些共用的格式后,就能够与系统中的其余处理程序来进行无缝交互,好比
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(“tel:555-2368”)); startActivity(intent);
就能够用来启动一个拨号程序。
定义好了参数格式,咱们在启用界面里就能够用
Uri data = Uri.parse("xxxx"); intent.setData(data);//传递参数
在子界面中,咱们用
Intent intent = getIntent(); Uri data = intent.getData();
来接收传来的参数
在子界面中,关闭界面时,也有肯定和取消之分,
咱们在点击肯定按钮时能够这样处理:
Uri data = Uri.parse("Content://" + edit.getText()); Intent result = new Intent(null, data); setResult(RESULT_OK, result);//传肯定信息,和参数 finish();
当点击取消按钮时,这样处理:
setResult(RESULT_CANCELED, null); //传取消信息,和参数 finish();
在父界面中,咱们经过一个
public void onActivityResult(int requestCode, int resultCode, Intent data)
继承函数来处理全部子界面的返回消息。这里面传来了请求代码,返回代码,和返回值,好比:
public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { Uri horse = data.getData(); TextView txt = (TextView)findViewById(R.id.TextView01); txt.setText(horse.toString()); } }
5.Android Intent传值 Serializable Parcelable
首先要注意的是,这种沉浸式状态栏的效果4.4系统及以上才会支持
方法很简单,在大家代码setContentView以前中加入版本判断:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //透明状态栏 getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); //透明导航栏 一些手机若是有虚拟键盘的话,虚拟键盘就会变成透明的,挡住底部按钮点击事件因此,最好不要用 //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); }
在对应的xml中想让状态栏和哪一个View的背景颜色融合,就在哪一个View中加入下面两行属性就好了
好比我想让状态栏和某一个ImageView的颜色融合
android:fitsSystemWindows="true" android:clipToPadding="true"
<ImageView android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:fitsSystemWindows="true" android:clipToPadding="true" android:src="@drawable/bg_lesson_normal" />
跳转方法:
/** * @Description: 跳转至其余应用 * @param appId 跳转到的APP的包名 * @param activityName 跳转到的APP的页面的类名全称 * @param bundle */ public void startOtherAPP(String appId, String activityName, Bundle bundle) { if (isAppInstalled(getActivity(), appId)) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); ComponentName comp = new ComponentName(appId, activityName); intent.setComponent(comp); int launchFlags = Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED; intent.setFlags(launchFlags); intent.setAction("android.intent.action.VIEW"); if (bundle != null) { intent.putExtras(bundle); } getActivity().startActivity(intent); } }
判断APP是否安装:
/** * @Description: 判断应用是否安装 * @param context * @param packagename 跳转到的APP的包名 * @return */ private boolean isAppInstalled(Context context, String packagename) { PackageInfo packageInfo; try { packageInfo = context.getPackageManager().getPackageInfo(packagename, 0); } catch (NameNotFoundException e) { packageInfo = null; e.printStackTrace(); } boolean isInstalled = (packageInfo == null) ? false : true; return isInstalled; }
经过包名和类名启动Activity:
Intent intent = new Intent(); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); intent.setPackage("com.hsae.d531mc.ipod"); intent.setClassName(mContext, "com.hsae.d531mc.ipod.view.MainActivity"); mContext.startActivity(intent);
十.Activity设置全屏
/** * 判断某个界面是否在前台 * * @param context * @param className * 某个界面名称 */ private boolean isForeground(Context context, String className) { if (context == null || TextUtils.isEmpty(className)) { return false; } ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> list = am.getRunningTasks(1); if (list != null && list.size() > 0) { ComponentName cpn = list.get(0).topActivity; if (className.equals(cpn.getClassName())) { return true; } } return false; }
添加权限:
<uses-permission android:name="android.permission.GET_TASKS"/>
使用:
//以MainActivity为例 boolean isShow = isForeground(this, MainActivity.class.getName()); app.shortToast("isForeground == " + isShow + ", className == " + MainActivity.class.getName()); Log.e("isShow", "isForeground == " + isShow + ", className == " + MainActivity.class.getName());