1、问题:TabActivity 用onKeyDown和onBackPress都监听不到back键
解决方案:使用dispatchKeyEvent(KeyEvent event)
2、问题:android.view.WindowLeaked异常
解决方案:这个问题一般是出现在使用Dialog或PopupWindow时,先把依附的Activity给finish掉了引起的。
3、启动APK的默认Activity
public static void startApkActivity(final Context ctx, String packageName) {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi;
try {
pi = pm.getPackageInfo(packageName, 0);
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setPackage(pi.packageName);
List<ResolveInfo> apps = pm.queryIntentActivities(intent, 0);
ResolveInfo ri = apps.iterator().next();
if (ri != null) {
String className = ri.activityInfo.name;
intent.setComponent(new ComponentName(packageName, className));
ctx.startActivity(intent);
}
} catch (NameNotFoundException e) {
Log.e("startActivity", e);
}
}
4、判断是否是平板(官方用法)
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
5、选择照片、视频、拍摄照片和拍摄视频
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);//照片
intent.setType("image/*");
startActivityForResult(intent,0);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);//视频
intent.setType("video/*");
startActivityForResult(intent,1);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//拍摄照片
cameraPicName = System.currentTimeMillis() + ".jpg";
File photofile = new File("/sdcard/farmer/" + cameraPicName);
Uri uri1 = Uri.fromFile(photofile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri1);
startActivityForResult(intent,2);
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);//拍摄视频
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
startActivityForResult(intent,3);
响应如下:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK)
{
String picUri = null;
switch (requestCode)
{
case 0:
case 1:
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (null != cursor)
{
cursor.moveToFirst();
picUri = cursor.getString(1);
if (uri.toString().contains("video"))
{
picName = cursor.getString(2);
picSize = cursor.getString(3);
}
else if (uri.toString().contains("images"))
{
picSize = cursor.getString(2);
picName = cursor.getString(3);
}
}
break;
case 2:
picUri = "/sdcard/farmer/" + cameraPicName;
File file1 = new File(picUri);
picSize = getFileSizeForB(file1) + "";
picName = file1.getName();
break;
case 3:
Uri uriVideo = data.getData();
Cursor cursor1 = this.getContentResolver().query(uriVideo, null, null, null, null);
if (null != cursor1 && cursor1.moveToNext())
{
picUri = cursor1.getString(1);
picName = cursor1.getString(2);
picSize = cursor1.getString(3);
}
break;
default:
break;
}
}
}
6、完整源代码详细解释——聊天、文件传输、语音呼叫,安卓版飞鸽传书软件
7、添加快捷方式:
private void addShortcut()
{
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");//添加快捷方式广播
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));//名称
shortcut.putExtra("duplicate", false);//不允许重复创建
//指定快捷方式启动的Activity,第二个参数必须加上点号(.),否则无法启动相应程序
ComponentName comp = new ComponentName(this.getPackageName(), "."+this.getLocalClassName());
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
ShortcutIconResource iconRes = Intent.ShortcutIconResource.fromContext(this, R.drawable.icon);//图标
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
sendBroadcast(shortcut);
}
删除快捷方式:
private void delShortcut()
{
Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
String appClass = this.getPackageName() + "." +this.getLocalClassName();
ComponentName comp = new ComponentName(this.getPackageName(), appClass);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(Intent.ACTION_MAIN).setComponent(comp));
sendBroadcast(shortcut);
}
this.getLocalClassName()可以改为需要跳转到的Activity的路径,且需要再AndroidManifest.xml 中加上<action android:name="android.intent.action.MAIN" />
9、文字超出定长"..."代替
android:singleLine="true"
android:maxWidth="150dip"
10、重写EditText,如:长按不弹出菜单
11、获取Task中的TopActivity
ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.d("TopTask", "pkg:"+cn.getPackageName());
Log.d("TopTask", "cls:"+cn.getClassName());
这样就可以获得当前的Task中最前端的那个Activity和它的包名了。
12、图片渐变特效,可用在页面切换或登录界面往主界面跳转的特效
ImageView iv=(ImageView)this.findViewById(R.id.imageBack);
AlphaAnimation aa=new AlphaAnimation(0.1f,1.0f);
aa.setDuration(10000);
iv.startAnimation(aa);
aa.setAnimationListener(new AnimationListener(){
@Override
public void onAnimationEnd(Animation arg0) {
Intent it=new Intent(Logo.this,MyLockScreen.class);
startActivity(it);
finish();
}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
13、常用UI处理代码
android自定义ProgressBar(仿淘宝)的加载效果
android中给图标加上数字(用于未接来电等等功能的提醒)
让Android自带的Gallery实现多点缩放,拖动和边界回弹效果,效果流畅
android 防止按钮连续点击的方法 [值得借鉴]
为SeekBar滑块设置固定值以及自定义Seekbar,progressbar样式
[Android] PorterDuff使用实例----实现新浪微博图片下载效果
在Android中实现IOS风格的SwitchButton按纽
Android自定义捕获Application全局异常优化版
17、调用个别手机拍照功能,会有横竖屏切换问题,导致原来的界面重写走了onCreate()方法,解决方法:
方法一:通过在onSaveInstanceState(Bundle savedInstanceState)中保存一些你需要的变量,
在onCreate()方法中判断savedInstanceState是否为null,不为null则调用onRestoreInstanceState()
方法取出之前存的变量来使用,这相当于重新加载了一边当前activity。
( 注:从Android 3.2 (API level 13)只后,android:configChanges="orientation|screenSize"。)
方法二:在activity中通过设置android:configChanges="orientation|keyboardHidden" 这个属性,
可以约束调用相机时,保持之前的那个activity竖屏状态不变,从而解决了activity重新加载的问题。 点击这里
18、判断手机是否已经root过
private void isExit(Context context){
File su = new File("/system/bin/su");
if (!su.exists())
{
Toast.makeText(context, "您的手机还没Root过", Toast.LENGTH_LONG).show();
}
}
19、Android 实现再按一次后退键退出应用程序
private boolean isexit = false;
private boolean hastask = false;
Timer texit = new Timer();
TimerTask task = new TimerTask(){
public void run(){
isexit = false;
hastask = true;
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
if (isexit == false){
isexit = true;
Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
if (!hastask){
texit.schedule(task, 2000);
}
}
else{
finish();
System.exit(0);
}
return false;
}
return super.onKeyDown(keyCode, event);
}
20、Intent的使用
Intent intent = new Intent();
//1.传数据
//intent.putExtra("company", "iflytek");
//intent.putExtra("age", 5);
//2.批量添加传递数据
Bundle bundle = new Bundle();
bundle.putString("company", "CSDN");
bundle.putInt("age", 10);
intent.putExtras(bundle);
//第一种方法
intent.setClass(this, OtherActivity.class); //设置要激活的组件
//第二种方法
//intent.setClassName(this, "cn.itcast.activitys.OtherActivity");
//第三种方法
//intent.setComponent(new ComponentName(this, OtherActivity.class));
//第四种方法 -- 显式Intent
//Intent intent = new Intent(this, OtherActivity.class);
//第5种方法 -- 跨应用激活Activity
//intent.setClassName("别的应用的包名", "别的应用的Activity");
//例-- intent.setClassName("cn.itcast.activitys", "cn.itcast.activitys.OtherActivity");
startActivity(intent);
//在OtherActivity关闭后,把处理的数据返回给MainActivity
//那必须在MainActivity打开时,选择startActivityForResult()
//startActivityForResult(intent, 200);
package com.kwstu.palmjn;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class UpladeActivity extends Activity {
private ImageView upload_img;
private ImageView upload_video;
private ImageView upload_imgtxt;
private ImageView upload_videotxt;
private ImageView img_img;
private Uri uri=null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uploadactivity);
// 动态设置标题
TextView title = (TextView) findViewById(R.id.title);
title.setText(IndexActivity.newTitle);
// 返回
ImageButton returnIdx = (ImageButton) findViewById(R.id.returnIdx);
returnIdx.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(UpladeActivity.this, IndexActivity.class);
startActivity(intent);
}
});
// 下一步
ImageButton next = (ImageButton) findViewById(R.id.next);
next.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText content = (EditText) findViewById(R.id.content);
// 先判断是否已经输入内容
if (content.getText().toString().trim().equals("")) {
Toast.makeText(UpladeActivity.this, "必须填写爆料内容!",
Toast.LENGTH_SHORT).show();
return;
} else if (IndexActivity.fileUrl.equals("")) {
Toast.makeText(UpladeActivity.this, "必须选择要爆料的媒体信息!",
Toast.LENGTH_SHORT).show();
return;
}
if (IndexActivity.userId != "" && IndexActivity.userId != "0") {
//执行下一步
Intent intent = new Intent();
intent.setClass(UpladeActivity.this, UploadInfo.class);
startActivity(intent);
}
else{
dialog();
}
}
});
// 上传图片按钮
upload_img = (ImageView) this.findViewById(R.id.upload_img);
upload_imgtxt = (ImageView) this.findViewById(R.id.upload_imgtxt);
upload_img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
uploadimg();
}
});
upload_imgtxt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
uploadimg();
}
});
// 上传视频按钮
upload_video = (ImageView) this.findViewById(R.id.upload_video);
upload_videotxt = (ImageView) this.findViewById(R.id.upload_videotxt);
upload_video.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
uploadvideo();
}
});
upload_videotxt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
uploadvideo();
}
});
Thread th1 = new Thread(new mythread());
th1.start();
}
// 登陆提示对话框
protected void dialog() {
AlertDialog.Builder builder = new Builder(UpladeActivity.this);
builder.setMessage("您尚未登陆,请先登陆。");
builder.setTitle("提示");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(UpladeActivity.this, Login.class);
startActivity(intent);
}
});
builder.create().show();
}
// 上传照片
protected void uploadimg() {
new AlertDialog.Builder(UpladeActivity.this)
.setTitle("选取上传图片")
.setItems(R.array.uploadimg,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
if (arg1 == 0)// 打开相机
{
File out = null;
Intent intentCamera = new Intent(
"android.media.action.IMAGE_CAPTURE");// 使用照相机
out = new File(Environment.getExternalStorageDirectory(), "camera.jpg");
uri = Uri.fromFile(out);
System.out.println("ddd"+uri);
intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intentCamera,
1);
}
if (arg1 == 1)// 读取图片
{
Intent intent = new Intent();
intent.setType("image/*");
//intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
/*
* 使用Intent.ACTION_GET_CONTENT这个Action
*/
intent.setAction(Intent.ACTION_GET_CONTENT);
/* 取得相片后返回本画面 */
startActivityForResult(Intent
.createChooser(intent, "使用以下打开方式"),
2);
}
}
}).show();
}
// 上传视频
protected void uploadvideo() {
new AlertDialog.Builder(UpladeActivity.this)
.setTitle("选取上传图片")
.setItems(R.array.uploadvideo,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
if (arg1 == 0)// 打开相机
{
Intent intent2 = new Intent();
intent2.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
File out = new File(Environment.getExternalStorageDirectory(), "camera.mp4");
uri = Uri.fromFile(out);
System.out.println("ddd"+uri);
intent2.putExtra(MediaStore.EXTRA_OUTPUT, uri);
intent2.putExtra(
MediaStore.EXTRA_VIDEO_QUALITY, 0); // 设置为低质量
startActivityForResult(intent2, 3);
}
if (arg1 == 1)// 读取图片
{
Intent intent = new Intent();
intent.setType("video/*");
/*
* 使用Intent.ACTION_GET_CONTENT这个Action
*/
intent.setAction(Intent.ACTION_GET_CONTENT);
/* 取得相片后返回本画面 */
startActivityForResult(Intent
.createChooser(intent, "使用以下打开方式"),
4);
}
}
}).show();
}
@Override
/**
* 利用ActivityResult传递图片参数
*
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println(requestCode+"----"+resultCode);
if (requestCode == 1) {
System.out.println("d----"+resultCode);
//if (data != null) {
System.out.println("这是拍摄上传图片");
// Uri u = Uri.parse(android.provider.MediaStore.EXTRA_OUTPUT);
// System.out.println(u.toString());
System.out.println("eee"+uri);
IndexActivity.fileUrl=uri.toString();
ContentResolver cr = this.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr
.openInputStream(uri));
/* 将Bitmap设定到ImageView */
upload_img.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
upload_img.setImageResource(R.drawable.nohot);
}
//Bundle extras = data.getExtras();
//Bitmap bitmap = (Bitmap) extras.get("data");
//upload_img.setImageBitmap(bitmap);
//} else {
//upload_img.setImageResource(R.drawable.nohot);
//}
}
if (requestCode == 2) {
System.out.println("d-d---"+resultCode);
if (resultCode == RESULT_OK) {
/*Uri uri = data.getData();
System.out.println(uri+"gg");
IndexActivity.fileUrl=uri.toString();
ContentResolver cr = this.getContentResolver();*/
try {
Bitmap bm = null;
//外界的程序访问ContentProvider所提供数据 可以通过ContentResolver接口
ContentResolver resolver = getContentResolver();
Uri originalUri = data.getData(); //获得图片的uri
bm = MediaStore.Images.Media.getBitmap(resolver, originalUri); //显得到bitmap图片
//这里开始的第二部分,获取图片的路径:
String[] proj = {MediaStore.Images.Media.DATA};
//好像是android多媒体数据库的封装接口,具体的看Android文档
Cursor cursor = managedQuery(originalUri, proj, null, null, null);
//按我个人理解 这个是获得用户选择的图片的索引值
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//将光标移至开头 ,这个很重要,不小心很容易引起越界
cursor.moveToFirst();
//最后根据索引值获取图片路径
String path = cursor.getString(column_index);
System.out.println(path+"path");
/*Bitmap bitmap = BitmapFactory.decodeStream(cr
.openInputStream(uri));
/* 将Bitmap设定到ImageView */
upload_img.setImageBitmap(bm);
} catch (FileNotFoundException e) {
upload_img.setImageResource(R.drawable.nohot);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (requestCode == 3) {
if (resultCode == RESULT_OK) {
System.out.println("这是拍摄上传视频");
/*
* Uri uri = data.getData(); System.out.println(uri);
* ContentResolver cr = this.getContentResolver(); try { Bitmap
* bitmap = BitmapFactory.decodeStream(cr
* .openInputStream(uri)); /* 将Bitmap设定到ImageView
* upload_img.setImageBitmap(bitmap); } catch
* (FileNotFoundException e) {
* upload_img.setImageResource(R.drawable.nohot); }
*/
}
}
if (requestCode == 4) {
if (resultCode == RESULT_OK) {
System.out.println("这是上传视频");
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (null != cursor)
{
cursor.moveToFirst();
String picUri = cursor.getString(1);
if (uri.toString().contains("video"))
{
String picName = cursor.getString(2);
String picSize = cursor.getString(3);
}
else if (uri.toString().contains("images"))
{
String picSize = cursor.getString(2);
String picName = cursor.getString(3);
}
}
//String[] proj = {MediaStore.Video.Media.DATA};
//好像是android多媒体数据库的封装接口,具体的看Android文档
//Cursor cursor = managedQuery(uri, proj, null, null, null);
//按我个人理解 这个是获得用户选择的图片的索引值
//String url = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
//将光标移至开头 ,这个很重要,不小心很容易引起越界
//cursor.moveToFirst();
//最后根据索引值获取图片路径
//String path = cursor.getString(column_index);
System.out.println(uri+"fffg");
/*ContentResolver cr = this.getContentResolver(); try { Bitmap
bitmap = BitmapFactory.decodeStream(cr
.openInputStream(uri));
/* 将Bitmap设定到ImageView
upload_img.setImageBitmap(bitmap); } catch
(FileNotFoundException e) {
upload_img.setImageResource(R.drawable.nohot); }*/
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Handler hd = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
// super.handleMessage(msg);
if (msg.what == 123) {
String jason = msg.obj.toString();
String filepath = Environment.getExternalStorageDirectory()
+ File.separator + jason;
Bitmap bitmap1 = BitmapFactory.decodeFile(filepath);
img_img.setImageBitmap(bitmap1);
}
}
};
class mythread implements Runnable {
public void run() {
// TODO Auto-generated method stub
HttpClient hc = new DefaultHttpClient();
// HttpPost hp = new
// HttpPost("http://172.16.3.250:8732/Mush/Host/Service/update_pictrue");
HttpPost hp = new HttpPost(IndexActivity.webserviceUrl
+ "UploadFileTesta");
HttpResponse hr;
InputStreamEntity reqEntity;
String path = Environment.getExternalStorageDirectory()
+ "/Movies/hhh.mp4";
File f = new File(path);
if (f.exists()) {
System.out.println("successful");
try {
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("SavePath", new StringBody("testVideo"));
entity.addPart("FileName", new StringBody("1"));
entity.addPart("FileData", (ContentBody) new FileBody(f));
hp.setEntity(entity);
reqEntity = new InputStreamEntity(
new FileInputStream(path), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if
// needed
hp.setEntity(reqEntity);
System.out.println("4");
HttpResponse response = hc.execute(hp);
System.out.println("5");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
// e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
}
}