Activity的切换
1. //从A到B,没有数据传递
Intent intent = newIntent();
Intent.setClass(A.this ,B.class);
startActivity(intent);
A.this.finish();
2. 两个Activity之间传递数据(简单)
//A数据传给B
//A中代码:”passData” 是自定义的识别标志,可以随便命名~ 还可以添加多个
Intent intent = new Intent();
intent.setClass(A.this, B.class);
Bundle mBundle = new Bundle();
mBundle.putString("passData", "ray'blog");//压入数据
intent.putExtras(mBundle);
startActivity(intent);
A.this.finish();
//B中接受数据的代码:
//读出数据,则data的值为 ray‘blog
Bundle bundle =getIntent().getExtras();
String data = bundle.getString( "passData" );
3. 两个Activity之间传递数据(复杂方法)
相关的几个函数
startActivityForResult
public final void setResult(intresultCode, String data)
回调函数
protected voidonActivityResult(int requestCode, int resultCode, Intent data)
例如A到B, 从B得到A的数据
//A到B
static final int RG_REQUEST = 0;
Intent intent = new Intent();
intent.setClass(A.this, B.class);
startActivityForResult(intent,RG_REQUEST);
//在B中处理
Bundle bundle = new Bundle();
bundle.putString("DataKey",edittext.getText().toString());//给bundle 写入数据
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
setResult(RESULT_OK, mIntent);
finish();
//最后在A的回调函数里面接收数据
if (requestCode == RG_REQUEST) {
if (resultCode ==RESULT_CANCELED)
setTitle("Canceled...");
elseif(resultCode == RESULT_OK) {
setTitle((String)data.getCharSequenceExtra("DataKey"));
}
}
4. 详解
一个Android应用程序很少会只有一个Activity对象,如何在多个Activity之间进行跳转,而且能够互相传值是一个很基本的要求。 在前面创建的MyApp中,我们通过点击按钮可以更新当前界面上的文本内容。现在我们想换种方式,在点击按钮后,显示一个新的屏幕,在这个屏幕上输入一段话,然后再返回到原先的界面显示刚才输入的那句话。 首先我们新建这个新屏幕的布局文件input.xml,并添加一个文本输入框和一个按钮(注意,xml元素的命名不要和其他布局文件中的定义重名,因为所有的资源都在R中进行索引,比如id,如果重名了在使用R.id.*的时候就会有问题了)。这个布局文件对应的是一个Activity,因此我们再新建一个Input类(继承自Activity)用于显示这个布局并响应事件。
然后,还有一个重要的工作,那就是在清单文件AndroidManifest.xml中告诉程序,我定义了一个新的Activity,你可以去调用它。
我们希望在以前的那个主界面上点击按钮以后可以跳转到文本输入界面,所以我们需要对按钮的onClick事件进行定义:
在这段代码里出现了一些新东西。首先是Intent,它是Android一个很重要的类.Intent直译是“意图”,什么是意图呢?比如你想从这个Activity跳转到另外一个Activity,这就是一个意图。它不但可以连接多个Activity,还可以在它们之间传递数据。在这里,我们就是用Intent从MyApp对象跳转到了Input对象。再看紧跟着的startActivityForResult()方法,顾名思义,它可以从一个定义好的Intent对象启动一个新的Activity,并且,这个Activity会返回执行的结果,这些内容下面马上就会提到。好,这里我们已经可以调出新Activity了,我们看一下执行的结果: 你马上可以想到,现在需要对新的Activity(Input)进行处理了。我们在点击“确定”按钮的时候,需要获得上面EditText对象中的文本,然后返回到前一个Activity(MyApp)中去。看我们的按钮事件处理:
这里的关键是SharedPreferences对象,这是在多个Activity(同一包中)共享数据的方式,本质上它就是一个可以在包的范围内进行数据共享的文件。 我们通过一个标签“Text”获得了和文本相关的那个SharedPreferences对象(“Text”仅仅是自己定义的一个标签),然后给它赋予一个“text”对象值为当前文本框中输入的文本。设置完成以后,设置当前Activity的执行结果为RESULT_OK,再关闭当前的Activity,剩下的事情就可以回到MyApp这个主界面中去执行了。 其实剩下的事情也很简单,在MyApp这个Activity中,我们需要重写一个函数,onActivityResult()。因为我们启动Input这个Activity的时候使用的是startActivityForResult()方法,这个方法会使Input执行完以后返回给MyApp一个结果,MyApp接收到返回结果的时候会触发onActivityResult事件,对于结果的处理就在onActivityResult()中进行。同样,我们通过“Text”这个标签获得SharedPreferences对象,再把字符串从“text”对象中取出来并显示到当前屏幕上。 另外说明一下,requestCode是用来标识请求对象,我们刚才在启动Activity的时候使用的是“startActivityForResult(intent, 0)”,这里的0就是requestCode,当然,你可以设置成任何你喜欢的值。
我们看一下执行结果:
调用浏览器 ,载入某网址
Uri uri = uri.parse(“http://www.baidu.com”);
Intent it = newIntent(Intent.ACTION_VIEW , uri)
startActivity(it);
Android 中打开浏览器
Intent viewIntent = new Intent(“android.intent.VIEW”, Uri.parse(“http://vaiyanzi.cnblogs.com”));
startActivity(ViewIntent);
15. 让图片旋转
Bitmap bitmapOrg =BitmapFactory.decodeResource(this.getContext().getResource() ,R.drawable.moon);
Matrix matrix = new Matrix();
matrix.postRotate(-90);//旋转的角度
Bitmap resizedBitmap =Bitmap.createBitmap(bitmapOrg , 0 ,0 bitmapOrg.getWidth() ,bitmapOrg.getHeight() , matrix , true);
BitmapDrawable bmd = newBitmapDrawable(resizedBitmap);
. 格式化string.xml
//in string.xml
Thanks for visiting %s. You age is %d!
//and in the java code;
String.format(getString(R.string.my_text), “oschina”,33);
1. 注册一个BroadcastReceiver
registerReceiver(mMasterResetReceiver , newIntentFilter(“oms.action.MASTERRESET”));
Private BroadcastReceiver mMasterResetReceiver =new BroadcastReceiver(){
Public voidonReceive(Context context , Intent intent){
String action =intent.getAction();
If(“oms.action.MASTERRESET”.equals(action)){
RecoverDefaultConfig();
}
}
}
2. 定义ContentObserver , 监听某个数据库
privateContentObserver mDownloadsObserver = newDownloadsChangeObserver(Downloads.CONTENT_URI);
privateDownloadsChangeObserver extends ContentObserver
{
publicDownloadsChangeObserver(Uri uri)
{
Super(new Handler());
}
@Override
Public voidonChange(boolean selfChange){}
}
9. 显示toast
Toast.makeText(this.getApplicationContext() ,R.id.item , Toast.LENGTH_SHORT).show();
//从资源文件string.xml 里面取提示信息
Toast.makeText(this,getString(R.string.welcome), Toast.LENGTH_SHORT).show();
12. 建立GPRS连接
//Dial the GPRS linlk
private boolean openDataConnection()
{
// Set up data connection
DataConnection conn =DataConnection.getInstance();
If(connectMode == 0){
ret =conn.openConnection(mContext , “cmwap” , “cmwap” , “cmwap”);
}else{
Ret =conn.openConnection(mContext , “cmnet”, “” , “”);
}
}
13. PreferenceActivity用法
public class Setting extends PreferenceActivity
{
public voidonCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferenceFromResource(R.xml.settings);
}
}
14. 通过HttpClient从指定的server 获取数据
DefaultHttpClient httpclient = newDefaultHttpClient();
HttpGet method = new HttpGet(“/templets/defaults/index.html”);
HttpResource resp;
Reader reader = nul;
try{
//AllClientPNames.TIMEOUT
HttpParams params = newBasicHttpParams();
params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);
httpClient.setParams(params);
resp =httpClient.execute(method);
int status =resp.getStatusLine().getStatusCode();
If(status !=HttpStatus.SC_OK)
{
Return false;
}
// HttpStatus.SC_OK;
return true;
}catch(ClientProtocolException e){
//TODO Auto-generatedcatch block
e.printStackTrace();
}catch (IOException e)
{
//TODO Auto-generatedcatch block
e.printStackTrace();
}finally{
If(reader != null)
Try{
reader.close();
}catch(IOException e)
{
//TODO Auto-generatedcatch block
e.printStackTrace();
}
}
22. Android中添加联系人
Public Uri addContact(Context context,){
ContentValues values =new ContentValues();
values.put(People.NAME ,name);
Uri uri =getContentResolver().insert(People.CONTENT_URI , values);
Uri numberUri =Uri.withAppendedPath(uri,People.Phones.CONTENT_DIRECTORY);
values.clear();
values.put(Contact.Phones.TYPE,People.Phones.TYPE_MOBILE);
values.put(People.NUMBER, phone);
getContentResolver().insert(numberUri, values);
return uri;
}
31. btn_selector
<?xml version = “1.0” encoding = “utf-8”?>
<selector xmlns:android=”http://schemas.android.com/apk/res/android”>
<!--pressed-->
<item android:state_pressed= “true”android:drawable=”@drawable/btn_press”/>
<!--focused-->
<itemandroid:state_focused=”true” android:drawable=”@drawable/btn”/>
<!--default-->
<itemandroid:drawable=”@drawable/btn”/>
</selector>
32. 关闭游标和数据库
private void close(Cursor cursor , SQLiteDatabasedatabase){
try{
if(cursor!=null&&!cursor.isClosed()){
Cursor.close();
}
}catch(Exception e){}
try {
dbHelper.closeDb(database);
}catch(Exception e){
}
}
33 MD5加密
Public static String md5(String string){
Byte[] hash;
try{
hash =MessageDigest.getInstance(“MD5”).digest(string.getBytes(“UTF-8”));
}catch(NoSuchAlgorithmExceptione){
throw newRuntimeException(“Huh , MD5 should be supported?” , e);
}catch(UnsupportedEncodingException e){
throw newRuntimeException(“Huh , UTF-8 should be supported?” , e);
}
StringBuilder hex = newStringBuilder(hash.length * 2);
for(byte b : hash){
if((b &0xFF)<0x10)hex.append(“0”);
hex.append(Integer.toHexString(b&0xFF));
}
returnhex.toString().toLowerCase();
}
36. 可以使用AlertDialog.Builder才产生一个提示框
例如像messagebox那样的
newAlertDialog.Builder(this)
.setTitle(“Android提示”)
.setMessage(“这是一个提示,请确定”)
.show();
带一个确定的对话框
NewAlertDialog.Builder(this);
.setMessage(“这是第二个提示”)
.setPositiveButton(“确定”,newDialogInterface.OnClickListener(){ public void onClick(DialogInterface , inti){//按钮事 件}})
.show();
AlertDialog.Builder还有很多复杂用法,有确定和取消的对话框
newAlertDialog.Builder(this)
.setTitle("提示")
.setMessage("确定退出?")
.setIcon(R.drawable.quit)
.setPositiveButton("确定", new DialogInterface.OnClickListener(){
public void onClick(DialogInterfacedialog, int whichButton) {
setResult(RESULT_OK);//确定按钮事件
finish();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int whichButton) {
//取消按钮事件
}
})
.show();
39. menu的用法
public static final intITEM_1_ID = Menu.FIRST;
public static final intITEM_2_ID = Menu.FIRST + 1;
public static final intITEM_3_ID = Menu.FIRST + 2;
public booleanonCreateOptionsMenu(Menu menu){
super.onCreateOptionMenu(menu);
//不带图标的Menu
menu.add(0 , ITEM_1_ID ,0 , “item-1”);
//带图标的Menu
menu.add(0, ITEM_2_ID , 0, “item-2”).setIcon(R.drawable.editbills2);
menu.add(0, ITEM_2_ID , 0, “item-2”).setIcon(R.drawable.editbills1);
return true;
}
public booleanonOptionItemSelected(MenuItem item){
Switch(item.getItemId()){
case 1:
Toast.makeText(this , “menu1”,TOAST.LENGTH_SHORT).show();
retrun true;
Case 2:
return true;
case 3:
return true;
}
Return false;
}
42. Android UI Layout
在 Android UI 中,最基本的构建单位(building block)是 android.view.View。一个 View 占据屏幕上的一个矩形区域,并负责该区域的绘画和事件处理。View 有一些子类,比如 ImageView、TextView 等可分别用来显示图像、文字…… View 还有一个特殊的子类 ViewGroup,ViewGroup 在 UI layout 中充当“容器”的角色,用以“包含”其他 View 以及 ViewGroup:
viewgroup.png
由于 ViewGroup 是一个 abstract class无法直接实例化,所以在 layout 中真正充当“容器”角色的应该是 ViewGroup 的子类 :AbsoluteLayout、 FrameLayout、 LinearLayout、 RelativeLayout 等。在实际的 UI 编程中,使用不同的 Layout 类作为容器,对该容器中的各个子 View 的排列方式有很大影响。比如,LinearLayout 中的各个子 View 按照横向或者纵向线性排列;而 AbsoluteLayout中各个子 View 可以指定以像素为单位的“绝对”位置。AbsoluteLayout 的这种“绝对”定位的布局方式和我们非常熟悉的 Windows 编程中的 SetWindowPos() 或 Form1.Left = 10 的布局方式是一样的,比较简单:
现在我们新建一个 Android 工程中,在其主 Activity 类中添加如下三个成员:
private AbsoluteLayout al;
private TextView tv;
private View v;
改写这个类的 onCreate 方法如下:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
//构造一个 AbsoluteLayout,设置其背景色
al = newAbsoluteLayout(this);
al.setBackgroundColor(Color.YELLOW);
//构造一个 TextView 并设置其 text 和 背景色
tv = newTextView(this);
tv.setText("Androidis a software stack for mobile devices that includes an operating system,middleware and key applications. ");
tv.setBackgroundColor(Color.BLUE);
// 用该 View 在父 View 中的 width,height,x,y 作为参数构造一个 AbsoluteLayout.LayoutParams
AbsoluteLayout.LayoutParams tvLP = new AbsoluteLayout.LayoutParams(70,50, 10, 20);
// 把这个 TextView 加入到 AbsoluteLayout中,并应用上一步创建的 LayoutParams。这样 TextView 就会显示在我 们指定的位置上了。
al.addView(tv, tvLP);
v = newView(this);
v.setBackgroundColor(Color.RED);
AbsoluteLayout.LayoutParams vLP = new AbsoluteLayout.LayoutParams(70,50, 90, 70);
//也可以先为子 View 设置 LayoutParams,然后再调用一个参数的ViewGroup.addView(View) 来添加。效果是一样 的。
v.setLayoutParams(vLP);
al.addView(v);
// 设置 al 为本 Activity 的 content
// 这样,在该 Activity 被调用时,就会显示该 AbsoluteLayout 和其子 View
this.setContentView(al);
}
43. Tab以及HostTab操作
Tab与TabHost
这就是Tab,而盛放Tab的容器就是TabHost
每一个Tab还对应了一个布局,这个就有点好玩了。一个Activity,对应了多个功能布局。
44. 监控应用程序包的安装&删除
方法 一:
public class getBroadcast extendsBroadcastReceiver{
@Override
public voidonReceive(Context context, Intent intent){
If(Intent.ACTION_PACKAGE_ADDED.equels(intent.getAction())){
Toast.makeText(context , “有应用被添加” ,Toast.LENGTH_SHORT ).show();
}elseif(Intent.ACTION_PACKAGE_REMOVED.equels(intent.getAction())){
Toast.makeText(context , “有应用被删除” ,Toast.LENGTH_SHORT ).show();
}elseif(Intent.ACTION_PACKAGE_REPLACED.equels(intent.getAction())){
Toast.makeText(context , “有应用被替换” ,Toast.LENGTH_SHORT ).show();
}elseif(Intent.ACTION_PACKAGE_BUTTON.equels(intent.getAction())){
Toast.makeText(context , “按键” ,Toast.LENGTH_SHORT ).show();
}
}
}
需要声明的权限如下AndroidManifest.xml
<receiver android:name="getBroadcast"android:enabled="true" >
<intent-filter>
<actionandroid:name="android.intent.action.PACKAGE_ADDED"></action>
<!-- <action android:name="android.intent.action.PACKAGE_CHANGED"></action>-->
<actionandroid:name="android.intent.action.PACKAGE_REMOVED"></action>
<actionandroid:name="android.intent.action.PACKAGE_REPLACED"></action>
<!-- <actionandroid:name="android.intent.action.PACKAGE_RESTARTED"></action>-->
<!-- <actionandroid:name="android.intent.action.PACKAGE_INSTALL"></action>-->
<actionandroid:name="android.intent.action.CAMERA_BUTTON"></action>
<dataandroid:scheme="package"></data>
</intent-filter>
</receiver>
方法 二:
通过阅读Android SDK里关于intent.action这部分里面的描述,我们可以找到一些与package相关的系统广播
android.intent.action.PACKAGE_ADDED
android.intent.action.PACKAGE_CHANGED
android.intent.action.PACKAGE_DATA_CLEARED
android.intent.action.PACKAGE_INSTALL
android.intent.action.PACKAGE_REMOVED
android.intent.action.PACKAGE_REPLACED
android.intent.action.PACKAGE_RESTARTED
android.intent.action.PACKAGE_ADDED
android.intent.action.PACKAGE_CHANGED
android.intent.action.PACKAGE_DATA_CLEARED
android.intent.action.PACKAGE_INSTALL
android.intent.action.PACKAGE_REMOVED
android.intent.action.PACKAGE_REPLACED
android.intent.action.PACKAGE_RESTARTED
其中 ACTION_PACKAGE_ADDED 在SDK里的描述是 :
Broadcast Action: A newapplication package has been installed on the device.
ACTION_PACKAGE_REMOVED 在SDK里的描述是 :
Broadcast Action: An existingapplication package has been removed from the device.
ACTION_PACKAGE_REPLACED 在SDK里的描述是 :
Broadcast Action: A new version ofan application package has been installed, replacing an existing version thatwas previously installed.
通过这三个广播消息 我们已经可以监控到Android 应用程序的安装和删除
详细的实现代码如下
package zy.Broadcast;
importandroid.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class getBroadcast extendsBroadcastReceiver {
@Override
public void onReceive(Context context,Intent intent) {
if(Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())){
Toast.makeText(context,"有应用被添加",Toast.LENGTH_LONG).show();
}
else if(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())){
Toast.makeText(context,"有应用被删除",Toast.LENGTH_LONG).show();
}
/* else if(Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())){
Toast.makeText(context,"有应用被改变",Toast.LENGTH_LONG).show();
}*/
else if(Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())){
Toast.makeText(context, "有应用被替换",Toast.LENGTH_LONG).show();
}
/* else if(Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())){
Toast.makeText(context,"有应用被重启",Toast.LENGTH_LONG).show();
}*/
/* else if(Intent.ACTION_PACKAGE_INSTALL.equals(intent.getAction())){
Toast.makeText(context,"有应用被安装",Toast.LENGTH_LONG).show();
}*/
}
}
然后在AndroidManifest.xml中声明这几个Action的<intent-filter>即可在系统里捕获这些广播消息
具体的源代码如下
<?xml version="1.0"encoding="utf-8"?>
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="zy.Broadcast"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon"android:label="@string/app_name">
<activityandroid:name=".Broadcast"
android:label="@string/app_name">
<intent-filter>
<actionandroid:name="android.intent.action.MAIN" />
<categoryandroid:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiverandroid:name="getBroadcast" android:enabled="true">
<intent-filter>
<actionandroid:name="android.intent.action.PACKAGE_ADDED"></action>
<!-- <actionandroid:name="android.intent.action.PACKAGE_CHANGED"></action>-->
<actionandroid:name="android.intent.action.PACKAGE_REMOVED"></action>
<actionandroid:name="android.intent.action.PACKAGE_REPLACED"></action>
<!-- <actionandroid:name="android.intent.action.PACKAGE_RESTARTED"></action>-->
<!-- <actionandroid:name="android.intent.action.PACKAGE_INSTALL"></action>-->
<dataandroid:scheme="package"></data>
</intent-filter>
</receiver>
</application>
<uses-sdk android:minSdkVersion="7" />
</manifest>
把程序安装之后 ,系统就会注册这个BroadcastReceiver
然后有应用安装删除替换操作时时,就会弹出Toast提示
删除应用
以上这样,我们就可以实现监控Android 应用程序的安装过程
至于拦截安装过程,我也正在研究中,大家有好的idea可以与我 分享,谢谢
45. uninstall apk
Uri uri = Uri.fromParts(“package”,strPackageName , null);
Intent it = new Intent(Intent.ACTION_DELETE , uri);
startActivity(it);
install apk
Uri installUri = Uri.fromParts(“package”,”xxx”,null);
Intent it = new Intent(Intent.ACTION_PACKAGE_ADDED , installUri);
45. 把一个字符串写进文件
public voidwriteFile(String str , String path){
File file;
FileOutputStream out;
try{
//创建文件
file= new File(path);
File.createNewFile();
//打开文件file的OutputStream
Out = newFileOutputStream(file);
String infoToWrite = str;
//将字符串转换成byte数组写入文件
out.write(infoToWrite.getBytes());
//关闭文件file的OutputStream
out.close();
}catch(IOException e){
//将出错信息打印到Logcat
DisplayToast(e.toString());
}
}
46. 把文件内容读出到一个字符串
public Stringgetinfo(String path){
File file;
String str = “”;
FileInputStream in;
try{
//打开文件
file = new File(path);
in = newFileInputStream(file);
//将文件内容全部读入到byte数组
int length =(int)file.length();
byte[] temp = newbyte[length];
In.read(temp ,0 ,length);
//将byte数组用UTF-8 编码并存入display字符串中
str =EncodingUtils.getString(temp , TEXT_ENCODING);
//关闭文件file的InputStream
In.close();
}catch(IOExcetion e){
DisplayToast(e.toString());
}
return str;
}
47. 调用Android installer 安装和卸载程序
Intent intent = newIntent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File("/sdcard/WorldCupTimer.apk")),"application/vnd.android.package-archive");
startActivity(intent); //安装 程序
Uri packageURI =Uri.parse("package:zy.dnh");
IntentuninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);//正常卸载程序
48. 结束某个进程
activityManager.restartPackage(packageName);
49. 设置默认来电铃声
public void setMyRingtone()
{
File k = new File("/sdcard/Shall We Talk.mp3"); // 设置歌曲路径
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, "Shall WeTalk");
values.put(MediaStore.MediaColumns.SIZE, 8474325);
values.put(MediaStore.MediaColumns.MIME_TYPE,"audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "Madonna");
values.put(MediaStore.Audio.Media.DURATION, 230);
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
// Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
Uri newUri = this.getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(this,RingtoneManager.TYPE_RINGTONE, newUri);
;}
需要的权限
<uses-permissionandroid:name="android.permission.WRITE_SETTINGS"></uses-permission>
50. 开机自启动
1. 定义一个BroadcastReceiver
代码:
public class BootReceiverextends BroadcastReceiver {
public void onReceive(Context ctx, Intentintent) {
Log.d("BootReceiver","system boot completed");
//start activity
Stringaction="android.intent.action.MAIN";
Stringcategory="android.intent.category.LAUNCHER";
Intent myi=newIntent(ctx,CustomDialog.class);
myi.setAction(action);
myi.addCategory(category);
myi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(myi);
//start service
Intent s=newIntent(ctx,MyService.class);
ctx.startService(s);
}
}
2. 配置Receiver的许可,允许接收系统启动消息,在AndroidManifest.xml中:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
配置Receiver,可以接收系统启动消息,在AndroidManifest.xml中
<receiver android:name=".app.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.HOME" />
</intent-filter>
</receiver>
启动模拟器,可以看到系统启动后,弹出一个对话框。
51. 打开照相机
Intent intent = newIntent(Intent.ACTION_CAMERA_BUTTON , null);
this.sendBroadcast(i);
long dateTaken =System.currentTimeMillis();
String name = createName(dateTaken)+“.jpg”;
filename = folder + name;
ContentValues values = newContentValiues();
values.put(Image.Media.TITLE ,fileName);
values.put(“_data” , fileName);
values.put(Images.Media.PICASA_ID ,fileName);
values.put(Images.Media.DISPLAY_NAME,fileName);
values.put(Images.Media.DESCRIPTION , fileName);
values.put(Images.ImageColumns.BUCKET_DISPLAY_NAME ,fileName);
Uri photoUri =getCOntentResolver().insert(Mediastore.Images.Media.EXTERNAL_CONTENT_URI ,values);
Intent intPhoto = newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
intPhoto.puExtra(MediaSore.EXTRA_OUTPUT , photoUri);
startActivityResult(intPhoto , 10);
52. 从gallery选取图片
Intent i = new Intent();
i.setType(“image/*”);
i.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(i , 11);
53. 打开录音机
Intent mi = newIntent(Media.RECORD_SOUND_ACTION);
startActivity(mi);
54. 显示应用详细列表
Uri uri = Uri.parse(“market://details?id=app_id”);
Intent it = newIntent(Intent.ACTION_VIEW , uri);
startActivity(it);
//where app_id is the application ID, findthe ID
//by clicking on your application on Markethome
//page, and notice the ID from the addressbar
刚才找app id未果,结果发现用package name也可以
Uri uri =Uri.parse("market://details?id=<packagename>");
这个简单多了
55. 寻找应用
Uri uri =Uri.parse("market://search?q=pname:pkg_name");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
//where pkg_name is the full package pathfor an application
56. intent action 大全
android.intent.action.ALL_APPS
android.intent.action.ANSWER
android.intent.action.ATTACH_DATA
android.intent.action.BUG_REPORT
android.intent.action.CALL
android.intent.action.CALL_BUTTON
android.intent.action.CHOOSER
android.intent.action.CREATE_LIVE_FOLDER
android.intent.action.CREATE_SHORTCUT
android.intent.action.DELETE
android.intent.action.DIAL
android.intent.action.EDIT
android.intent.action.GET_CONTENT
android.intent.action.INSERT
android.intent.action.INSERT_OR_EDIT
android.intent.action.MAIN
android.intent.action.MEDIA_SEARCH
android.intent.action.PICK
android.intent.action.PICK_ACTIVITY
android.intent.action.RINGTONE_PICKER
android.intent.action.RUN
android.intent.action.SEARCH
android.intent.action.SEARCH_LONG_PRESS
android.intent.action.SEND
android.intent.action.SENDTO
android.intent.action.SET_WALLPAPER
android.intent.action.SYNC
android.intent.action.SYSTEM_TUTORIAL
android.intent.action.VIEW
android.intent.action.VOICE_COMMAND
android.intent.action.WEB_SEARCH
android.net.wifi.PICK_WIFI_NETWORK
android.settings.AIRPLANE_MODE_SETTINGS
android.settings.APN_SETTINGS
android.settings.APPLICATION_DEVELOPMENT_SETTINGS
android.settings.APPLICATION_SETTINGS
android.settings.BLUETOOTH_SETTINGS
android.settings.DATA_ROAMING_SETTINGS
android.settings.DATE_SETTINGS
android.settings.DISPLAY_SETTINGS
android.settings.INPUT_METHOD_SETTINGS
android.settings.INTERNAL_STORAGE_SETTINGS
android.settings.LOCALE_SETTINGS
android.settings.LOCATION_SOURCE_SETTINGS
android.settings.MANAGE_APPLICATIONS_SETTINGS
android.settings.MEMORY_CARD_SETTINGS
android.settings.NETWORK_OPERATOR_SETTINGS
android.settings.QUICK_LAUNCH_SETTINGS
android.settings.SECURITY_SETTINGS
android.settings.SETTINGS
android.settings.SOUND_SETTINGS
android.settings.SYNC_SETTINGS
android.settings.USER_DICTIONARY_SETTINGS
android.settings.WIFI_IP_SETTINGS
android.settings.WIFI_SETTINGS
android.settings.WIRELESS_SETTINGS
57. Android的动作、广播、类别等标志大全
String BATTERY_CHANGED_ACTION 广播:充电状态,或者电池的电量发生变化"android.intent.action.BATTERY_CHANGED"
StringBOOT_COMPLETED_ACTION 广播:在系统启动后,这个动作被广播一次(只有一次) "android.intent.action.BOOT_COMPLETED"
StringCALL_FORWARDING_STATE_CHANGED_ACTION 广播:语音电话的呼叫转移状态已经改变 "android.intent.action.CFF"
StringCONFIGURATION_CHANGED_ACTION 广播:设备的配置信息已经改变,参见Resources.Configuration."android.intent.action.CONFIGURATION_CHANGED" Creator CREATOR 无 无
StringDATA_ACTIVITY_STATE_CHANGED_ACTION 广播:电话的数据活动(data activity)状态(即收发数据的状态)已经改变。"android.intent.action.DATA_ACTIVITY"
StringDATA_CONNECTION_STATE_CHANGED_ACTION 广播:电话的数据连接状态已经改变 "android.intent.action.DATA_STATE"
StringDATE_CHANGED_ACTION 广播:日期被改变"android.intent.action.DATE_CHANGED"
StringFOTA_CANCEL_ACTION 广播:取消所有被挂起的 (pending)更新下载"android.server.checkin.FOTA_CANCEL"
StringFOTA_INSTALL_ACTION 广播:更新已经被确认,马上就要开始安装"android.server.checkin.FOTA_INSTALL"
StringFOTA_READY_ACTION 广播:更新已经被下载,可以开始安装"android.server.checkin.FOTA_READY"
StringFOTA_RESTART_ACTION 广播:恢复已经停止的更新下载"android.server.checkin.FOTA_RESTART"
StringFOTA_UPDATE_ACTION 广播:通过 OTA 下载并安装操作系统更新 "android.server.checkin.FOTA_UPDATE"
StringMEDIABUTTON_ACTION 广播:用户按下了“MediaButton” "android.intent.action.MEDIABUTTON"
StringMEDIA_BAD_REMOVAL_ACTION 广播:扩展介质(扩展卡)已经从 SD 卡插槽拔出,但是挂载点 (mount point) 还没解除(unmount) "android.intent.action.MEDIA_BAD_REMOVAL"
StringMEDIA_EJECT_ACTION 广播:用户想要移除扩展介质(拔掉扩展卡) "android.intent.action.MEDIA_EJECT"
StringMEDIA_MOUNTED_ACTION 广播:扩展介质被插入,而且已经被挂载"android.intent.action.MEDIA_MOUNTED"
StringMEDIA_REMOVED_ACTION 广播:扩展介质被移除。"android.intent.action.MEDIA_REMOVED"
StringMEDIA_SCANNER_FINISHED_ACTION 广播:已经扫描完介质的一个目录"android.intent.action.MEDIA_SCANNER_FINISHED"
StringMEDIA_SCANNER_STARTED_ACTION 广播:开始扫描介质的一个目录"android.intent.action.MEDIA_SCANNER_STARTED"
StringMEDIA_SHARED_ACTION 广播:扩展介质的挂载被解除(unmount),因为它已经作为 USB 大容量存储被共享 "android.intent.action.MEDIA_SHARED"
StringMEDIA_UNMOUNTED_ACTION 广播:扩展介质存在,但是还没有被挂载(mount) "android.intent.action.MEDIA_UNMOUNTED"
String MESSAGE_WAITING_STATE_CHANGED_ACTION广播:电话的消息等待(语音邮件)状态已经改变 "android.intent.action.MWI"
StringTIMEZONE_CHANGED_ACTION 广播:时区已经改变"android.intent.action.TIMEZONE_CHANGED"
StringTIME_CHANGED_ACTION 广播:时间已经改变(重新设置) "android.intent.action.TIME_SET"
String TIME_TICK_ACTION广播:当前时间已经变化(正常的时间流逝) "android.intent.action.TIME_TICK"
StringUMS_CONNECTED_ACTION 广播:设备进入 USB 大容量存储模式 "android.intent.action.UMS_CONNECTED"
StringUMS_DISCONNECTED_ACTION 广播:设备从 USB 大容量存储模式退出"android.intent.action.UMS_DISCONNECTED"
String WALLPAPER_CHANGED_ACTION广播:系统的墙纸已经改变"android.intent.action.WALLPAPER_CHANGED"
StringXMPP_CONNECTED_ACTION 广播:XMPP 连接已经被建立 "android.intent.action.XMPP_CONNECTED"
StringXMPP_DISCONNECTED_ACTION 广播:XMPP 连接已经被断开 "android.intent.action.XMPP_DI
String NETWORK_TICKLE_RECEIVED_ACTION广播:设备收到了新的网络 "tickle" 通知"android.intent.action.NETWORK_TICKLE_RECEIVED"
StringPACKAGE_ADDED_ACTION 广播:设备上新安装了一个应用程序包"android.intent.action.PACKAGE_ADDED"
StringPACKAGE_REMOVED_ACTION 广播:设备上删除了一个应用程序包"android.intent.action.PACKAGE_REMOVED"
StringPHONE_STATE_CHANGED_ACTION 广播:电话状态已经改变"android.intent.action.PHONE_STATE"
StringPROVIDER_CHANGED_ACTION 广播:更新将要(真正)被安装"android.intent.action.PROVIDER_CHANGED"
StringPROVISIONING_CHECK_ACTION 广播:要求 polling ofprovisioning service 下载最新的设置"android.intent.action.PROVISIONING_CHECK"
StringSCREEN_OFF_ACTION 广播:屏幕被关闭"android.intent.action.SCREEN_OFF"
StringSCREEN_ON_ACTION 广播:屏幕已经被打开"android.intent.action.SCREEN_ON"
StringSERVICE_STATE_CHANGED_ACTION 广播:电话服务的状态已经改变"android.intent.action.SERVICE_STATE"
StringSIGNAL_STRENGTH_CHANGED_ACTION 广播:电话的信号强度已经改变"android.intent.action.SIG_STR"
StringSTATISTICS_REPORT_ACTION 广播:要求 receivers 报告自己的统计信息"android.intent.action.STATISTICS_REPORT"
StringSTATISTICS_STATE_CHANGED_ACTION 广播:统计信息服务的状态已经改变"android.intent.action.STATISTICS_STATE_CHANGED"
StringBROWSABLE_CATEGORY 类别:能够被浏览器安全使用的activities 必须支持这个类别"android.intent.category.BROWSABLE"
StringALTERNATIVE_CATEGORY 类别:说明 activity 是用户正在浏览的数据的一个可选操作 "android.intent.category.ALTERNATIVE"
StringDEFAULT_CATEGORY 类别:如果 activity 是对数据执行确省动作(点击, center press)的一个选项,需要设置这个类别。 "android.intent.category.DEFAULT"
StringFRAMEWORK_INSTRUMENTATION_TEST_CATEGORY 类别:Tobe used as code under test for framework instrumentation tests."android.intent.category.FRAMEWORK_INSTRUMENTATION_TEST"
StringGADGET_CATEGORY 类别:这个 activity 可以被嵌入宿主 activity (activity that is hosting gadgets)。 "android.intent.category.GADGET"
StringHOME_CATEGORY 类别:主屏幕 (activity),设备启动后显示的第一个 activity "android.intent.category.HOME"
StringLAUNCHER_CATEGORY 类别:Activity 应该被显示在顶级的 launcher 中"android.intent.category.LAUNCHER"
StringPREFERENCE_CATEGORY 类别:activity是一个设置面板 (preference panel)"android.intent.category.PREFERENCE"
StringSAMPLE_CODE_CATEGORY 类别:To be used as ansample code example (not part of the normal user experience)."android.intent.category.SAMPLE_CODE"
StringSELECTED_ALTERNATIVE_CATEGORY 类别:对于被用户选中的数据,activity是它的一个可选操作"android.intent.category.SELECTED_ALTERNATIVE"
StringTAB_CATEGORY 类别:这个 activity 应该在 TabActivity 中作为一个 tab 使用"android.intent.category.TAB"
StringTEST_CATEGORY 类别:作为测试目的使用,不是正常的用户体验的一部分"android.intent.category.TEST"
StringUNIT_TEST_CATEGORY 类别:应该被用作单元测试(通过 test harness 运行)"android.intent.category.UNIT_TEST"
StringWALLPAPER_CATEGORY 类别:这个 activity 能过为设备设置墙纸 "android.intent.category.WALLPAPER"
StringDEVELOPMENT_PREFERENCE_CATEGORY 类别:说明 activity 是一个设置面板 (development preference panel)."android.intent.category.DEVELOPMENT_PREFERENCE"
StringEMBED_CATEGORY 类别:能够在上级(父)activity中运行 "android.intent.category.EMBED"
StringDELETE_ACTION 动作:从容器中删除给定的数据"android.intent.action.DELETE"
StringDEFAULT_ACTION 动作:和 VIEW_ACTION 相同,是在数据上执行的标准动作 "android.intent.action.VIEW"
StringDIAL_ACTION 动作:拨打数据中指定的电话号码 "android.intent.action.DIAL"
String EDIT_ACTION动作:为制定的数据显示可编辑界面 "android.intent.action.EDIT"
StringEMERGENCY_DIAL_ACTION 动作:拨打紧急电话号码"android.intent.action.EMERGENCY_DIAL"
StringGET_CONTENT_ACTION 动作:让用户选择数据并返回。"android.intent.action.GET_CONTENT"
StringINSERT_ACTION 动作:在容器中插入一个空项 (item)。"android.intent.action.INSERT"
StringLOGIN_ACTION 动作:获取登录凭证。"android.intent.action.LOGIN"
StringMAIN_ACTION 动作:作为主入口点启动,不需要数据 "android.intent.action.MAIN"
StringSETTINGS_ACTION 动作:显示系统设置。输入:无"android.intent.action.SETTINGS"
StringSYNC_ACTION 动作:执行数据同步 "android.intent.action.SYNC"
StringWALLPAPER_SETTINGS_ACTION 动作:显示选择墙纸的设置界面。输入:无"android.intent.action.WALLPAPER_SETTINGS"
StringWEB_SEARCH_ACTION 动作:执行 web 搜索 "android.intent.action.WEB_SEARCH"
StringVIEW_ACTION 动作:向用户显示数据 "android.intent.action.VIEW"
StringSENDTO_ACTION 动作:向 data 指定的接收者发送一个消息 "android.intent.action.SENDTO"
StringRUN_ACTION 动作:运行数据(指定的应用),无论它(应用)是什么 "android.intent.action.RUN"
StringPICK_ACTION 动作:从数据中选择一个项目 (item),将被选中的项目返回 "android.intent.action.PICK"
StringPICK_ACTIVITY_ACTION 动作:选择一个 activity,返回被选择的 activity 的类(名) "android.intent.action.PICK_ACTIVITY"
StringADD_SHORTCUT_ACTION 动作:在系统中添加一个快捷方式"android.intent.action.ADD_SHORTCUT"
StringALL_APPS_ACTION 动作:列举所有可用的应用"android.intent.action.ALL_APPS"
String ANSWER_ACTION动作:处理拨入的电话"android.intent.action.ANSWER"
StringBUG_REPORT_ACTION 动作:显示 activity 报告错误 "android.intent.action.BUG_REPORT"
StringCALL_ACTION 动作:拨打电话,被呼叫的联系人在数据中指定 "android.intent.action.CALL"
StringCLEAR_CREDENTIALS_ACTION 动作:清除登陆凭证(credential) "android.intent.action.CLEAR_CREDENTIALS"
StringTEMPLATE_EXTRA 附加数据:新记录的初始化模板"android.intent.extra.TEMPLATE"
StringINTENT_EXTRA 附加数据:和PICK_ACTIVITY_ACTION一起使用时,说明用户选择的用来显示的activity和ADD_SHORTCUT_ACTION一起使用的时候,描述要添加的快捷方式 2010-08-19
"android.intent.extra.INTENT"
StringLABEL_EXTRA 附加数据:大写字母开头的字符标签,和 ADD_SHORTCUT_ACTION 一起使用
"android.intent.extra.LABEL"
intMULTIPLE_TASK_LAUNCH 启动标记:和NEW_TASK_LAUNCH 联合使用,禁止将已有的任务改变为前景任务 (foreground)。 8 0x00000008
intNEW_TASK_LAUNCH 启动标记:设置以后,activity 将成为历史堆栈中的第一个新任务(栈顶) 4 0x00000004
intNO_HISTORY_LAUNCH 启动标记:设置以后,新的 activity不会被保存在历史堆栈中 1 0x00000001
intSINGLE_TOP_LAUNCH 启动标记:设置以后,如果 activity已经启动,而且位于历史堆栈的顶端,将不再启动(不重新启动) activity 2 0x00000002
intFORWARD_RESULT_LAUNCH 启动标记:如果这个标记被设置,而且被一个已经存在的 activity 用来启动新的 activity,已有 activity 的回复目标 (reply target) 会被转移给新的 activity。 16
0x00000010
58. 打开另一个程序
Intent i = new Intent();
ComponentName cn =newComponentName(“com.yellowbook.android2”);
i.setComponnent(cn);
i.setAction(“android.intent.action.MAIN”);
startActivtiyForResult(i,RESULT_OK);
59.Android退出当前程序的方法
android.os.Process.killProcess(android.os.Process.myPid());
60. 很多应用都有一个在用户后退的时候显示“再按一次退出”的提醒,这个怎么实现呢?有两种方式
第一种方式(最常用)
long waitTime = 2000;
long touchTime = 0;
@Override
public boolean onKeyDown(int keyCode ,keyEvent event){
if(event.getAction() ==KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode){
longcurrentTime = System.currentTimeMillis();
if((currentTime- touchTime)>=waitTime){
//让Toast的显示时间和等待时间相同
Toast.makText(this,“再按一次退出”, (int)waitTime).show();
touchTime= currentTime;
}else{
finish();
}
return true;
}
return super.onKeyDown(keyCode ,event);
}
第二种方式
重写onBackPressed方法直接监听返回键
@Override
public void onBackPressed(){
long currentTime =System.currentTimeMillis();
if((currentTime-touchTime)>=waitTime){
//让Toast的显示时间和等待时间相同
Toast.makText(this,“再按一次退出”, (int)waitTime).show();
touchTime= currentTime;
}else{
finish();
}
}
这种方法虽然写法简单,但是这种方法只适用于Android2.0以后
如果你需要同时重写这两个方法,可能需要注意一些问题啦!系统先是onKeyDown,如果returntrue了,就不会onBackPressed了。
61. Android程序如何升级
用户可以从market上直接下载下来直接安装就可以了,会自动识别覆盖的,除非你把版本调低了。
<manifest xmlns=http://schemas.android.com/apk/res/android
package = “com.xx.xx”包名
android:versionCode = “x”//版本号
android:versionName = “xxx”//版本名
/>
就是修改这个versionCode和versionName
代码安装apk
Intent i = new Intent(Intent.ACTION_VIEW);
String filePath = “/sdcard/xxx.apk”;
i.setDataAndType(Uri.parse(“file://filePath”,”application/vnd.android.package-archive”));
context.startActivity(i);
程序卸载
Intent itent = newIntent(Intent.ACTION_DELETE,uri);
Intent.startActivity();
文件下载
DownloadProvider的权限级别改成normal了就可以使用了网上也有说明
首先要在Android Manifest.xml中申请访问Downloadmanager的权限
1. <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER"/>
1. ContentValues values = new ContentValues();
2. values.put(Downloads.URI, url);//指定下载地址
3. values.put(Downloads.COOKIE_DATA, cookie);//如果下载Server需要cookie,设置cookie
values.put(Downloads.VISIBILITY,Downloads.VISIBILITY_HIDDEN);//设置下载提示是否在屏幕顶部显示
4. values.put(Downloads.NOTIFICATION_PACKAGE,getPackageName());//设置下载完成之后回调的包名
5. values.put(Downloads.NOTIFICATION_CLASS,DownloadCompleteReceiver.class.getName());//设置下载完成之后负责接收的Receiver,这个类要继承 BroadcastReceiver
6. values.put(Downloads.DESTINATION,save_path);//设置下载到的路径,这个需要在Receiver里自行处理
7. values.put(Downloads.TITLE,title);//设置下载任务的名称
8. this.getContentResolver().insert(Downloads.CONTENT_URI,values);//将其插入到DownloadManager的数据库中,数据库会触发修改事件,启动下载任务
9. ContentValues values = new ContentValues();
10. values.put("uri", uri.toString());
11. values.put("useragent", "Mozilla/5.0(Linux; U; Android 1.5; en-us; sdk Build/CUPCAKE) AppleWebKit/528.5+ (KHTML,like Gecko) Version/3.1.2 Mobile Safari/525.20.1");
12. values.put("notificationpackage", getPackageName());
13. values.put("notificationclass","HelloWorld");
14. values.put("visibility", 1);
15. values.put("mimetype", mimetype);
16. values.put("hint", filename);
17. values.put("description", uri.getHost());
18. values.put("total_bytes",1349528);
19.
20. mResolver =getContentResolver();
21. mResolver.insert(Uri.parse("content://downloads/download"),values);
62. packagecom.android;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entity;
import org.ksoap2.SoapEnvelope;
importorg.ksoap2.serialization.SoapObject;
importorg.ksoap2.serialization.SoapPrimitive;
importorg.ksoap2.serialization.SoapSerialiizationEnvelope;
importorg.ksoap2.transport.AndroidHttpTransport;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnCLickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extendsActivity{
//显示结果的listview
ListView listview =null;
//输入文本框
EditText provinceEdit = null;
//用于存放数据的集合list
List<Map<String,Object>>data = null;
//提示对话框
ProgressDialog myDialog = null;
//收索按钮
Button searchButton = null;
/* called when the activity isfirst created */
@Override
public void onCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
provinceEdit =(EditText)this.findViewById(R.id.provinceEdit);
//获得搜索按钮
searchButton = (Button)this.findViewById(R.id.searchButton);
//为搜索按钮添加单击监听事件
searchButton.setOnClickListener(newOnClickListener(){
public voidonClick(View v){
//响应按钮单机事件的函数
ResponseOnCLick();
}
});
}
//响应按钮单机事件的函数
public void ResponseOnClick(){
//创建一个线程
HttpThreadthread = new HttpThread(handler);
//构造请求参数
HashMap<String, Object> params = new HashMap<String , Object>();
1. try{
2. CharSequenceetValue=provinceEdit.getText();
3. String name=”";
4. if(etValue!=null){
5. //字符转码
6. name=new String(etValue.toString().getBytes(),”UTF-8″);
7.
8. }
9. params.put(“byProvinceName”, name);
10. }catch(Exception ex){
11. ex.printStackTrace();
12. }
13.
14. //
15. Stringurl=”http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx”;
16. // String url =”http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx”;
17. String nameSpace =”http://WebXml.com.cn/”;
18. String methodName =”getSupportCity”;
19. // 开始新线程进行WebService请求
20. thread.doStart(url, nameSpace,methodName, params);
21.
22. }
23. /**
24. * 捕获消息队列
25. *
26. */
27. Handler handler=new Handler(){
28.
29. public voidhandleMessage(Message m){
30. ArrayList <String>myList=(ArrayList<String>)m.getData().getStringArrayList(“data”);
31.
32. if(myList !=null){
33. if(data!=null){
34. data.clear();
35. }else{
36. data=new ArrayList<Map <String,Object>>();
37. }
38.
39. for(inti=0;i<myList.size();i++){
40. Map<String, Object> item=new HashMap<String,Object>();
41. item.put(“text”, myList.get(i));
42. data.add(item);
43. }
44.
45. /**
46. * 列表显示
47. *
48. */
49. SimpleAdaptersimpleAdapter=new SimpleAdapter(MainActivity.this
50. ,data,R.layout.listlayout,new String[] {“text”},new int []{R.id.showData});
51. listView=(ListView)findViewById(R.id.showListView);
52. listView.setAdapter(simpleAdapter);
53. }
54. }
55. };
56. /**
57. * 线程类
58. * @author Administrator
59. *
60. */
61.
62. public class HttpThread extendsThread{
63. private Handler handle=null;
64. Stringurl=null;
65. StringnameSpace=null;
66. StringmethodName=null;
67. HashMap <String ,Object> params=null;
68. ProgressDialog progressDialog=null;
69.
70. //构造函数
71. publicHttpThread(Handler hander){
72. handle=hander;
73. }
74.
75. /**
76. * 启动线程
77. */
78. publicvoid doStart(String url, String nameSpace, String methodName,
79. HashMap<String, Object> params) {
80. // TODOAuto-generated method stub
81. this.url=url;
82. this.nameSpace=nameSpace;
83. this.methodName=methodName;
84. this.params=params;
85.
86. progressDialog=ProgressDialog.show(MainActivity.this, ”提示”,”正在请求请稍等……”, true);
87. this.start();
88. }
89. /**
90. * 线程运行
91. */
92. @Override
93. public void run(){
94. // TODO Auto-generated method stub
95. System.out.println(“jack”);
96. super.run();
97. try{
98. //web service请求
99. SoapObjectresult=(SoapObject) CallWebService();
100. //构造数据
101. ArrayList<String>list=null;
102. if(result !=null&& result.getPropertyCount() > 0){
103. list=new ArrayList<String>();
104.
105. for(int i=0;i<result.getPropertyCount();i++){
106. SoapPrimitivevalue=(SoapPrimitive) result.getProperty(i);
107. list.add(value.toString());
108. }
109.
110. //a取消进度对话框
111. progressDialog.dismiss();
112. //构造消息
113. Message message=handle.obtainMessage();
114. Bundle b=new Bundle();
115. b.putStringArrayList(“data”, list);
116. message.setData(b);
117. handle.sendMessage(message);
118. }
119. }catch(Exception ex){
120. ex.printStackTrace();
121. }finally{
122.
123. }
124. }
125.
126. /**
127. * 请求web service
128. */
129. protected ObjectCallWebService(){
130. String SOAP_ACTION = nameSpace + methodName;
131. //创建SoapObject实例
SoapObject request=newSoapObject(nameSpace,methodName);
132. //生成调用web service方法的soap请求消息
SoapSerializationEnvelope envelope=newSoapSerializationEnvelope(SoapEnvelope.VER11);
133. //设置.net web service
134. envelope.dotNet=true;
135. //发送请求
136. envelope.setOutputSoapObject(request);
137. //请求参数
138. if(params != null && !params.isEmpty() ){
139. for(Iterator=params.entrySet().iterator();it.hasNext();){
140. Map.Entrye=(Entry) it.next();
141. request.addProperty(e.getKey().toString(),e.getValue()); }
142. }
143. //
144. AndroidHttpTransportandroidHttpTrandsport=new AndroidHttpTransport(url);
145. SoapObject result=null;
146. try{
147. //web service请求
148. androidHttpTrandsport.call(SOAP_ACTION, envelope);
149. //得到返回结果
150. result=(SoapObject)envelope.getResponse();
151. }catch(Exception ex){
152. ex.printStackTrace();
153. }
154. return result;
155.
156. }
157. }
158. }
}
63. Android有未接来电后的处理(判断未接来电)
在Android的手机状态中没有未接来电的监听器,所以如果想当手机有未接来电后进行处理,这时候就需要自己对手机的状态判断是未接来电后再进行处理.
实现思路:
1,继承PhoneStateListener后,当手机的状态改变后将会触发onCallStateChanged.手机的状态分为CALL_STATE_RINGING(响铃中),CALL_STATE_IDLE(空闲),CALL_STATE_OFFHOOK(忙音).
2,记录上一次的手机状态,如果的手机现在的空闲,上次的状态响铃中的话,就可以判断是未接来电.
不足:
1,我现在的处理不能判断出是用户是否主动不接电话.
实现步骤:
1,编写CallListener,处理手机状态变更监听,当状态改变时进行处理。如果想知道如何在Android发送短信可以看我另一博文[Android中发送短信(sms)]
1. package rbase.app.smshelpmate.call.listener;
2.
3. import java.text.MessageFormat;
4.
5. import rbase.app.smshelpmate.Config;
6. import rbase.app.smshelpmate.R;
7. import rbase.app.smshelpmate.call.enums.CallStateEnum;
8. import rbase.app.smshelpmate.forward.ForwardManager;
9. import rbase.app.smshelpmate.forward.enums.ForwardType;
10.import rbase.app.smshelpmate.forward.vo.ForwardParam;
11.import android.content.Context;
12.import android.telephony.PhoneStateListener;
13.import android.telephony.TelephonyManager;
14.import android.util.Log;
15.
16./**
17.* @author www.r-base.net
18.*/
19.public class CallListener extends PhoneStateListener {
20. private staticfinal String TAG = "sms";
21. private static intlastetState = TelephonyManager.CALL_STATE_IDLE; // 最后的状态
22. private Contextcontext;
23.
24. public CallListener(Contextcontext) {
25. super();
26. this.context = context;
27. }
28.
29. public voidonCallStateChanged(int state, String incomingNumber) {
30. Log.v(TAG, "CallListener call state changed : " +incomingNumber);
31. String m = null;
32.
33. // 如果当前状态为空闲,上次状态为响铃中的话,则破觚为认为是未接来电
34. if(lastetState== TelephonyManager.CALL_STATE_RINGING
35. && state ==TelephonyManager.CALL_STATE_IDLE){
36. sendSmgWhenMissedCall(incomingNumber);
37. }
38.
39. // 最后的时候改变当前值
40. lastetState = state;
41. }
42.
43. private voidsendSmgWhenMissedCall(String incomingNumber) {
44. //... 进行未接来电处理(发短信,发email等等通知)
45. }
46.}
复制代码
2,编写CallReceiver,注册来电广播接收器。
1. package rbase.app.smshelpmate.call.service;
2.
3. import rbase.app.smshelpmate.Const;
4. import rbase.app.smshelpmate.call.listener.CallListener;
5. import android.content.BroadcastReceiver;
6. import android.content.Context;
7. import android.content.Intent;
8. import android.os.Bundle;
9. import android.telephony.PhoneStateListener;
10.import android.telephony.TelephonyManager;
11.import android.util.Log;
12.
13./**
14.* @author www.r-base.net
15.*/
16.public class CallReceiver extends BroadcastReceiver{
17. public voidonReceive(Context context, Intent intent) {
18. Log.i("sms", "CallReceiver Start...");
19. TelephonyManager telephony = (TelephonyManager) context
20. .getSystemService(Context.TELEPHONY_SERVICE);
21. CallListener customPhoneListener = newCallListener(context);
22.
23. telephony.listen(customPhoneListener,
24. PhoneStateListener.LISTEN_CALL_STATE);
25.
26. Bundle bundle = intent.getExtras();
27. String phoneNr =bundle.getString("incoming_number");
28. Log.i("sms", "CallReceiver Phone Number :" + phoneNr);
29. }
30.}
复制代码
3,在AndroidManifest.xml中的application节点下添加如下代码.进行注册电话状态改变广播接收.
1. <manifest ...>
2. <application ...>
3. <receiver android:name=".call.service.CallReceiver">
4. <intent-filter android:priority="100">
5. <actionandroid:name="android.intent.action.PHONE_STATE" />
6. </intent-filter>
7. </receiver>
8. </application>
9. </manifest>
4,在AndroidManifest.xml中添加读取手机状态的权限.
<uses-permissionandroid:name="android.permission.READ_PHONE_STATE" />
总结:
通过以上的步骤,当手机有未接来电时 sendSmgWhenMissedCall 该方法就会触发,就可以进行相应的处理.本人的其中一个应用(RBase短信助手) 就是用以上的代码实现了当手机有未接来电后可以发短信给指定的手机进行通知.
64. 关闭应用
当应用不再使用时,通常需要关闭应用,可以使用以下两种方法关闭android应用:
第一种方法:首先获取当前进程的id,然后杀死该进程。 (建议使用)
android.os.Process.killProcess(android.os.Process.myPid())
第二种方法:终止当前正在运行的Java虚拟机,导致程序终止
System.exit(0);
第三种方法:强制关闭与该包有关联的一切执行
ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
manager.restartPackage(getPackageName());
<uses-permissionandroid:name="android.permission.RESTART_PACKAGES" />
65.高循环效率的代码
/*
* How To Write Faster Loops (after Dan Bornstein, GoogleEngineer)
*
* - http://www.youtube.com/watch?v=ptjedOZEXPM
*
*/
/* 1 (fastest) */
for (int i = initializer; i >= 0; i--) { ... }
/* 2 */
int limit = calculateLoopLimit();
for (int i = 0; i < limit; i++) { ... }
/* 3 */
Type[] array = getMyArray();
for (Type obj : array) { ... }
/* 4 */
for (int i = 0; i < array.length; i++) { ... }
/* 5 */
for (int i = 0; i < this.var; i++) { ... }
/* 6 */
for (int i = 0; i < obj.size(); i++) { ... }
/* 7 (slowest) */
Iterable<Type> list = getMyList();
for (Type obj : list) { ... }
66.监听短信内容
AndroidManifest.xml中添加
<receiverandroid:name=".receive">
<intent-filter>
<actionandroid:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permissionandroid:name="android.permission.READ_SMS"></uses-permission>
再写一个广播监听
public class receive extendsBroadcastReceiver
{
String receiveMsg = "";
public void onReceive(Context context, Intent intent)
{
SmsMessage[] msg= null;
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED"))
{
//StringBuilder buf = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[])bundle.get("pdus");
msg= newSmsMessage[pdusObj.length];
for (int i = 0;i<pdusObj.length; i++)
msg[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
}
for(int i = 0; i < msg.length; i++)
{
String msgTxt = msg[i].getMessageBody();
if (msgTxt.equals("Testing!"))
{
Toast.makeText(context, "success!", Toast.LENGTH_LONG).show();
return;
}
else
{
Toast.makeText(context, msgTxt, Toast.LENGTH_LONG).show();
return;
}
}
return;
}
}
3.获得对话框中EditText内容
1.对话框布局文件:xml==== R.layout.dlg_testself.xml
<?xml version="1.0"encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:text="请输入…: "
android:gravity="left"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<EditText
android:id="@+id/testdaysnum"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginLeft="20dip"
android:layout_marginRight="20dip"
android:scrollHorizontally="true"
android:autoText="false"
android:capitalize="none"
android:gravity="fill_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
2.Java代码中生成对话框代码
2.1 声明:
private ProgressDialog m_Dialog;
2.2 实现对话框代码:
LayoutInflater factory = LayoutInflater.from(ChooseThings.this);
//得到自定义对话框
final View testDialogView= factory.inflate(R.layout.dlg_testself, null);
final EditTextedit_GetDaysNum = (EditText) testDialogView.findViewById( R.id.testdaysnum );
//创建对话框
AlertDialog.Builder testDialog = new AlertDialog.Builder(ChooseThings.this);
testDialog.setTitle("提示: ");
testDialog.setView( testDialogView);//设置自定义对话框的样式
testDialog.setPositiveButton("确定", //设置"确定"按钮
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//输入完成后,点击“确定”开始登陆
String nullOrNot = edit_GetDaysNum.getText().toString();
if( !TextUtils.isEmpty(nullOrNot ) ) {
intgetDaysNumFromDlg = Integer.parseInt(edit_GetDaysNum.getText().toString() ); //将editText中的内容转为int型
}
m_Dialog = ProgressDialog.show (ChooseThings.this, "请等待...", "正在为您计算...", true);
new Thread() {
public void run() {
try {
sleep(3000);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
//登录结束,取消m_Dialog对话框
m_Dialog.dismiss();
Intent intent = new Intent();
intent.setClass(ChooseThings.this, TestResult.class);
startActivity( intent );
// ChooseThings.this.finish();
}
}
}.start();
}
});
testDialog.setNeutralButton("查看详细",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
testDialog.setNegativeButton("取消", //设置“取消”按钮
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//点击"取消"按钮之后退出程序
}
})
.create();//创建
testDialog.show();//显示
18.标题栏进度框显示的简单方法
很多网友可能发现,比如Android自带的浏览器在载入网页时等待时间可能会在标题栏的右上角有一个小圆圈在不断旋转,由于其不包含具体进度,很多网友可能没有找到详细的操作方法在SDK中。作为标题栏进度指示器其实属于Activity类的方法。
在setContentView之前声明:
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);,
在需要显示进度时调用 setProgressBarIndeterminateVisibility(true);
停止时调用 setProgressBarIndeterminateVisibility(false);
37.显示网页
Uri uri =Uri.parse(\"http://www.google.com\");Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);
本文详细介绍了Android中Activity的切换方法,包括无数据传递、简单数据传递和复杂数据传递,涉及Intent、Bundle、startActivityForResult以及onActivityResult等关键函数。同时,讲解了在Activity间如何使用startActivityForResult进行数据交换,以及如何处理返回结果。此外,还提到了通过SharedPreferences进行数据共享。

848

被折叠的 条评论
为什么被折叠?



