您的位置:首页 > 移动开发 > Android开发

Android:实用代码(开启启动、建立GPRS连接、闹钟等)

2012-04-21 18:06 483 查看
[b]1:查看是否有存储卡插入[/b]String status=Environment.getExternalStorageState();

if(status.equals(Enviroment.MEDIA_MOUNTED))

{

说明有SD卡插入

}

[b]2:让某个Activity透明[/b] OnCreate中不设Layoutthis.setTheme(R.style.Theme_Transparent);以下是Theme_Transparent的定义(注意transparent_bg是一副透明的图片)

[b]3:在屏幕元素中设置句柄[/b]

使用Activity.findViewById来取得屏幕上的元素的句柄. 使用该句柄您可以设置或获取任何该对象外露的值.

TextView msgTextView = (TextView)findViewById(R.id.msg);

msgTextView.setText(R.string.push_me);

[b]4:发送短信[/b] String body=”this is mms demo”; Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”smsto”, number, null));

mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);

mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true);

mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true);

startActivity(mmsintent);

[b]5:发送彩信[/b] StringBuilder sb = new StringBuilder(); sb.append(”file://”); sb.append(fd.getAbsoluteFile()); Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”mmsto”, number,
null));

// Below extra datas are all optional.

intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);

intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);

intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());

intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);

intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent); startActivity(intent);

[b]6:发送Mail[/b] mime = “img/jpg”;

shareIntent.setDataAndType(Uri.fromFile(fd), mime);

shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fd));

shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject); shareIntent.putExtra(Intent.EXTRA_TEXT, body);

[b]7:注册一个BroadcastReceiver[/b]registerReceiver(mMasterResetReciever, new IntentFilter(”OMS.action.MASTERRESET”));private BroadcastReceiver mMasterResetReciever = new BroadcastReceiver() { public void onReceive(Context context,
Intent intent){

String action = intent.getAction();

if(”oms.action.MASTERRESET”.equals(action)){

RecoverDefaultConfig();

}

} };

[b]8:定义ContentObserver,监听某个数据表[/b]

private ContentObserver mDownloadsObserver = new DownloadsChangeObserver(Downloads.CONTENT_URI);private class DownloadsChangeObserver extends ContentObserver {

public DownloadsChangeObserver(Uri uri) {

super(new Handler()); } @Override

public void onChange(boolean selfChange) {}

}

[b]9:获得 手机UA[/b] public String getUserAgent()

{

String user_agent = ProductProperties.get(ProductProperties.USER_AGENT_KEY, null);

return user_agent;

}

[b]10:清空手机上Cookie[/b] CookieSyncManager.createInstance(getApplicationContext());

CookieManager.getInstance().removeAllCookie();

[b]11:建立GPRS连接[/b] //Dial the GPRS link.

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”, “”, “”);

} }

12:PreferenceActivity 用法

public class Setting extends PreferenceActivity{ public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

addPreferencesFromResource(R.xml.settings);

}}Setting.xml: Android:key=”seting2″

android:title=”@string/seting2″

android:summary=”@string/seting2″/> android:key=”seting1″

android:title=”@string/seting1″

android:summaryOff=”@string/seting1summaryOff”

android:summaryOn=”@stringseting1summaryOff”/>

[b]13:通过HttpClient从指定server获取数据[/b]
DefaultHttpClient httpClient = new DefaultHttpClient();

HttpGet method = new HttpGet(“http://www.baidu.com/1.html”);

HttpResponse resp;

Reader reader = null;

try {

// AllClientPNames.TIMEOUT

HttpParams params = new BasicHttpParams();

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-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {

if (reader != null) try {

reader.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

[b]14:显示toast[/b]

Toast.makeText(this._getApplicationContext(), R.string._item, Toast.LENGTH_SHORT).show();
15:屏幕显示
程序中默的显示是带有标题栏和系统信息栏的,有的时候,这很影响程序界面的美观。手机默认的是竖屏,或与感应器状态相关,为了某种效果,我们的程序需要限制使用横屏或竖屏。以下的代码就解决了上述问题。

//设置为无标题栏

requestWindowFeature(Window.FEATURE_NO_TITLE);

//设置为全屏模式

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

//设置为横屏

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

16:Intent传参 当Activity与Activity/Service(或其它情况)有时与要进行参数传递,最常用也是最简单的方式就是通过Intent来处理。

看如下代码:

Intent intent = new Intent(...);

Bundle bundle = new Bundle();

bundle.putString("NAME", "zixuan");

intent.putExtras(bundle);

context.startActivity(intent); 或 context.startService(intent);

当然,有传送就有接收,接收也很简单,如:

Bundle bunde = intent.getExtras();

String name = bunde.getInt("NAME");

当然参数KEY要与传送时的参数一致。

17:获取手机号 在j2me中,根本没有办法获取用户的手机号码,就连获取手机串号(IMEI)都基本上无法实现,然后在android手机上一切都是如此的简单,看代码:

TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);

String imei = tm.getDeviceId();

String tel = tm.getLine1Number();

看来,android的确加速了j2me的消亡。

18:振动器 总感觉手机上的振动器没有多大用处(当然静音模式下的振铃很有用),但还是顺带着说一下吧,只有两行代码:

1、获取振动服务的实例

Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

2、设置振动时长,单位当然也是ms

vibrator.vibrate(1000);

如果你觉得这样过去单调的话,可以设个节奏:

vibrator.vibrate(new long[]{10, 100, 20, 200}, -1);

两个参数,习惯告诉我第一个是节奏,第二个是重复次数,可事实并没有这么简单,我翻译不好,大家还是看原文吧:

public void vibrate (long[] pattern, int repeat)

pattern: an array of longs of times to turn the vibrator on or off.

repeat: the index into pattern at which to repeat, or -1 if you don't want to repeat.

google喜欢弄些技巧,我却觉得这里有点弄巧成拙了。

19:闹钟管理 最近看了一下Android的闹钟管理类(AlarmManager),真不错误,强大又简单,代码如下:

1、建立一个AlarmReceiver继承入BroadcastReceiver,并在AndroidManifest.xml声明

public static class AlarmReceiver extends BroadcastReceiver {

@Override

public void onReceive(Context context, Intent intent) {

Toast.makeText(context, "闹钟提示:时间到!", Toast.LENGTH_LONG).show();

}

}

复制代码

2、建立Intent和PendingIntent,来调用目标组件。

Intent intent = new Intent(this, AlarmReceiver.class);

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

复制代码

3、设置闹钟

获取闹钟管理的实例:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

复制代码

设置单次闹钟:

alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5*1000), pendingIntent);

复制代码

设置周期闹钟:

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10*1000), (24*60*60*1000), pendingIntent);

复制代码
20:开机自启动1.定义一个BroadcastReceiver

public class BootReceiver extends BroadcastReceiver {

public void onReceive(Context ctx, Intent intent) {

Log.d("BootReceiver", "system boot completed");

//start activity

String action="android.intent.action.MAIN";

String category="android.intent.category.LAUNCHER";

Intent myi=new Intent(ctx,CustomDialog.class);

myi.setAction(action);

myi.addCategory(category);

myi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

ctx.startActivity(myi);

//start service

Intent s=new Intent(ctx,MyService.class);

ctx.startService(s);

}

}

复制代码

2.配置Receiver的许可,允许接收系统启动消息,在AndroidManifest.xml中:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

复制代码

3.配置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>

复制代码

4.启动模拟器,可以看到系统启动后,弹出一个对话框。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: