本文主要是对Android服务相关知识的总结,详细内容看代码。
1.首先是主界面MainActivity.java
/**
* 有关服务的学习
*
*/
public class MainActivity extends Activity {
private String TAG="MainActivity";
/**参数设置*/
Button startServiceButton;// 启动服务按钮
Button shutDownServiceButton;// 关闭服务按钮
Button startBindServiceButton;// 启动绑定服务按钮
Button sendBroadcast;// 使用广播
Button notificationButton;// 使用通知功能
Button alarmButton;// 使用闹钟
Button handlerButton;// 使用handler
Button asyncButton;// 使用异步加载
Button phoneStateButton;// 查看手机状态
Button callphoneButton;// 拨打电话
Button vibratorButton;// 使用震动
CountService countService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "setContentView");
setContentView(R.layout.main);
getWidget();
registListener();
}
/**获得组件*/
public void getWidget(){
startServiceButton = (Button)findViewById(R.id.startServerButton);
startBindServiceButton = (Button)findViewById(R.id.startBindServerButton);
shutDownServiceButton = (Button)findViewById(R.id.sutdownServerButton);
sendBroadcast = (Button)findViewById(R.id.sendBroadcast);
notificationButton = (Button)findViewById(R.id.notification);
alarmButton = (Button)findViewById(R.id.alarm);
handlerButton = (Button)findViewById(R.id.handler);
asyncButton = (Button)findViewById(R.id.async);
phoneStateButton = (Button) findViewById(R.id.phonestate);
callphoneButton = (Button) findViewById(R.id.callphone);
vibratorButton = (Button) findViewById(R.id.vibrator);
}
/**为按钮添加监听*/
public void registListener(){
startServiceButton.setOnClickListener(startService);
shutDownServiceButton.setOnClickListener(shutdownService);
startBindServiceButton.setOnClickListener(startBinderService);
sendBroadcast.setOnClickListener(broadcastReceiver);
notificationButton.setOnClickListener(notification);
phoneStateButton.setOnClickListener(phonestate);
vibratorButton.setOnClickListener(vibrator);
callphoneButton.setOnClickListener(callphoneEvent);
alarmButton.setOnClickListener(startAlarm);
handlerButton.setOnClickListener(handler);
asyncButton.setOnClickListener(async);
}
/**启动服务的事件监听*/
public Button.OnClickListener startService = new Button.OnClickListener(){
public void onClick(View view){
/**单击按钮时启动服务*/
Intent intent = new Intent(MainActivity.this,CountService.class);
startService(intent);
Log.d(TAG, "start Service");
}
};
/**关闭服务*/
public Button.OnClickListener shutdownService = new Button.OnClickListener(){
public void onClick(View view){
/**单击按钮时启动服务*/
Intent intent = new Intent(MainActivity.this,CountService.class);
/**退出Activity是,停止服务*/
stopService(intent);
Log.d(TAG, "shutDown serveice");
}
};
/**打开绑定服务的Activity*/
public Button.OnClickListener startBinderService = new Button.OnClickListener(){
public void onClick(View view){
/**单击按钮时启动服务*/
Intent intent = new Intent(MainActivity.this,UseBriderActivity.class);
startActivity(intent);
Log.d(TAG, "start Binder Service");
}
};
/**打开广播学习的按钮*/
public Button.OnClickListener broadcastReceiver = new Button.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this,UseBroadcastActivity.class);
startActivity(intent);
Log.d(TAG,"start broadcast");
}
};
/**打开通知*/
public Button.OnClickListener notification = new Button.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, UseNotificationActivity.class);
startActivity(intent);
Log.d(TAG,"start Notification");
}
};
public Button.OnClickListener phonestate= new Button.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, UsePhoneStateActivity.class);
startActivity(intent);
Log.d(TAG,"start phonestate");
}
};
public Button.OnClickListener vibrator= new Button.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, UseVibratorActivity.class);
startActivity(intent);
Log.d(TAG,"start vibrator");
}
};
public Button.OnClickListener callphoneEvent= new Button.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, UseActionCallActivity.class);
startActivity(intent);
Log.d(TAG,"start callphone");
}
};
/**使用闹钟*/
public Button.OnClickListener startAlarm = new Button.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, UseAlarmManagerActivity.class);
startActivity(intent);
Log.v("MainStadyService ","start alarm");
}
};
//使用handler
public Button.OnClickListener handler= new Button.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, UseHandleMessageActivity.class);
startActivity(intent);
Log.d(TAG,"start handle");
}
};
//使用异步加载
public Button.OnClickListener async= new Button.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, UseAsyncTaskActivity.class);
startActivity(intent);
Log.v("MainStadyService ","start handle");
}
};
/**
* 销毁活动
*/
protected void onDestroy(){
super.onDestroy();
Intent intent = new Intent(MainActivity.this,CountService.class);
/**退出Activity是,停止服务*/
stopService(intent);
}
}
2.然后是主界面相关的布局文件main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="24dip"
android:layout_gravity="center"
android:text="服务学习"/>
<Button
android:id="@+id/startServerButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="启动普通服务"
/>
<Button
android:id="@+id/sutdownServerButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="停止普通服务"
/>
<Button
android:id="@+id/startBindServerButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="启动绑定服务服务"
/>
<Button
android:id="@+id/sendBroadcast"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="发送广播"
/>
<Button
android:id="@+id/notification"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="使用通知"
/>
<Button
android:id="@+id/alarm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" 打开闹钟"
/>
<Button
android:id="@+id/handler"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" 使用handler"
/>
<Button
android:id="@+id/async"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" 使用异步加载"
/>
<Button
android:id="@+id/phonestate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" 获取手机状态"
/>
<Button
android:id="@+id/callphone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" 拨打电话"
/>
<Button
android:id="@+id/vibrator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" 使用震动"
/>
</LinearLayout>
</ScrollView>
3.服务的启动与停止相关Service:CountService.java
这个类中新开了一个线程,并每隔一秒打印出一行日志
/**
* 计数的服务
*/
public class CountService extends Service{
private String TAG="CountService";
/**创建参数*/
boolean threadDisable ;
int count;
public IBinder onBind(Intent intent){
return null;
}
public void onCreate(){
super.onCreate();
/**创建一个线程,每秒计数器加一,并在控制台进行Log输出*/
new Thread(new Runnable(){
public void run(){
while(!threadDisable){
try{
Thread.sleep(1000);
}catch(InterruptedException e){
}
count++;
Log.d(TAG,"Count is:"+count);
}
}
}).start();
}
public void onDestroy(){
super.onDestroy();
/**服务停止时,终止计数进程*/
this.threadDisable = true;
}
public int getCount(){
return count;
}
class ServiceBinder extends Binder{
public CountService getService(){
return CountService.this;
}
}
}
4.绑定服务 UseBriderActivity.java
/**
* 通过bindService和unBindSerivce的方式启动和结束服务
*/
public class UseBriderActivity extends Activity {
private String TAG="UseBriderActivity";
/**参数设置*/
CountService countService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new UseBriderFace(this));
Intent intent = new Intent(UseBriderActivity.this,CountService.class);
/**进入Activity开始服务*/
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
private ServiceConnection conn = new ServiceConnection(){
/**获取服务对象时的操作*/
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
countService = ((CountService.ServiceBinder)service).getService();
}
/**无法获取到服务对象时的操作*/
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
countService =null;
}
};
protected void onDestroy(){
super.onDestroy();
this.unbindService(conn);
Log.d(TAG, "out");
}
}
5.绑定服务的跳转界面UseBriderFace.java
public class UseBriderFace extends View{
/**创建参数*/
public UseBriderFace(Context context){
super(context);
}
@SuppressLint("DrawAllocation")
public void onDraw(Canvas canvas){
canvas.drawColor(Color.WHITE);//画白色背景
/**绘制文字*/
Paint textPaint = new Paint();
textPaint.setColor(Color.RED);
textPaint.setTextSize(30);
canvas.drawText("使用绑定服务", 10, 30, textPaint);
textPaint.setColor(Color.GREEN);
textPaint.setTextSize(18);
canvas.drawText("使用绑定服务后,这个Activity关闭后", 20, 60, textPaint);
canvas.drawText("绑定的服务也会关闭", 5, 80, textPaint);
}
}
6.发送广播UseBroadcastActivity.java
/**
* 使用Broadcast,这是一个发送广播的类
*/
public class UseBroadcastActivity extends Activity{
private String TAG="UseBroadcastActivity";
/**创建参数*/
private Button sendBroadcast;
/**创建Activity*/
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.broadcast);// 使用布局文件
getView();
sendBroadcast.setOnClickListener(sendBroadcastClick);// 添加事件监听
}
//获取控件
public void getView(){
sendBroadcast = (Button)findViewById(R.id.sendBroadcast);
}
/**创建事件监听*/
public Button.OnClickListener sendBroadcastClick = new Button.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent();// 创建意图
intent.putExtra("CONTENT", "This is a Broadcast demo");// 设置广播的内容
intent.setAction("com.example.myservicedemo");// 设置广播的Action
sendBroadcast(intent);
}
};
}
7.广播接收器UseBroadcastReceiver.java
/**这是一个接收广播的类*/
public class UseBroadcastReceiver extends BroadcastReceiver{
private String TAG="UseBroadcastReceiver";
public void onReceive(Context context, Intent intent){
Log.d(TAG, "I get a message");
}
}
8.发送广播的布局文件broadcast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/sendBroadcast"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="发送广播"
/>
</LinearLayout>
9.使用通知功能UseNotificationActivity.java
/**使用notification*/
public class UseNotificationActivity extends Activity {
/**创建组件*/
private Button textButton;
private Button soundButton;// 声音通知
private Button vibrateButton;// 震动通知
private Button ledButton;// led通知
private Button offButton;// 关闭通知
NotificationManager notificationManager;
/**创建Activity*/
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
getComment();
registerComment();
}
/**获取对象*/
public void getComment(){
/**获取Notification对象*/
notificationManager = (NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
textButton = (Button)findViewById(R.id.notificationMessage);
soundButton =(Button)findViewById(R.id.notificationSound);
vibrateButton = (Button)findViewById(R.id.notificationVibrate);
ledButton = (Button)findViewById(R.id.notificationLED);
offButton = (Button)findViewById(R.id.offnotification);
}
/**注册对象*/
public void registerComment(){
textButton.setOnClickListener(notificationMessage);
soundButton.setOnClickListener(notificationSound);
vibrateButton.setOnClickListener(notificationVibrate);
ledButton.setOnClickListener(notificationLed);
offButton.setOnClickListener(notificationOff);
}
public Button.OnClickListener notificationMessage = new Button.OnClickListener(){
public void onClick(View view){
Notification notification = new Notification();// 创建Notification对象
notification.icon = R.drawable.icon;
notification.tickerText = "This is text notication";// 设置通知消息
/**单击通知后的Intent,此例子单击后还是在当前页面*/
PendingIntent intent = PendingIntent
.getActivity(UseNotificationActivity.this,
0, new Intent(UseNotificationActivity.this,UseNotificationActivity.class)
, 0);
/**设置通知消息*/
notification.setLatestEventInfo(UseNotificationActivity.this
,"Notification","Content of Notification Demo",intent);
/**执行通知*/
notificationManager.notify(0, notification);
}
};
public Button.OnClickListener notificationSound = new Button.OnClickListener(){
public void onClick(View view){
/**创建通知对象*/
Notification notification = new Notification();
/**获取系统当前声音*/
String ringName = RingtoneManager.getActualDefaultRingtoneUri(
UseNotificationActivity.this, RingtoneManager.TYPE_RINGTONE)
.toString();
/**设置系统当前铃声为此通知的铃声*/
notification.sound = Uri.parse(ringName);
/**执行通知*/
notificationManager.notify(0,notification);
}
};
/**震动通知*/
public Button.OnClickListener notificationVibrate = new Button.OnClickListener(){
public void onClick(View view){
Notification notification = new Notification();// 创建Notification对象
notification.vibrate = new long[] {0, 100, 200, 300};// 设置通知震动模式
notificationManager.notify(0,notification);// 执行通知
}
};
/**LED通知*/
public Button.OnClickListener notificationLed = new Button.OnClickListener(){
public void onClick(View view){
Notification notification = new Notification();// 创建Notification对象
notification.ledOnMS = 300;// 设置led开始闪光的时间
notification.ledOffMS = 1000;// 设置关闭时的闪光时间
notificationManager.notify(0,notification);// 执行通知
}
};
/**关闭通知*/
public Button.OnClickListener notificationOff = new Button.OnClickListener(){
public void onClick(View view){
notificationManager.cancel(0);// 关闭通知
}
};
}
10.通知功能的布局文件notification.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/notificationMessage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="文字通知"
/>
<Button
android:id="@+id/notificationSound"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="声音通知"
/>
<Button
android:id="@+id/notificationVibrate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="震动通知"
/>
<Button
android:id="@+id/notificationLED"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="LED通知"
/>
<Button
android:id="@+id/offnotification"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="关闭通知"
/>
</LinearLayout>
11.打开闹钟功能UseAlarmManagerActivity.java
public class UseAlarmManagerActivity extends Activity {
/**创建参数*/
private Button startAlarm;
private Button shutdownAlarm;
private AlarmManager alarm;
/**创建Activity*/
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.usealarmmanager);
getWidget();
}
//获取控件
public void getWidget(){
startAlarm = (Button)findViewById(R.id.startAlarm);
shutdownAlarm = (Button)findViewById(R.id.shutDowntAlarm);
alarm = (AlarmManager)getSystemService(ALARM_SERVICE);// 获取AlarmManager
}
//为控件注册监听器
public void registerWidget(){
startAlarm.setOnClickListener(startAlarms);
shutdownAlarm.setOnClickListener(shutdownAlarms);
}
/**启动闹钟*/
public Button.OnClickListener startAlarms = new Button.OnClickListener(){
public void onClick(View view){
// 设置10秒后出发闹钟
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());// 设置calendar的时间
calendar.add(Calendar.SECOND, 10);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), null);
}
};
public Button.OnClickListener shutdownAlarms = new Button.OnClickListener(){
public void onClick(View view){
alarm.cancel(null);
}
};
}
12.打开闹钟的相应界面
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="@+id/startAlarm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="十秒后打开闹钟"
/>
<Button
android:id="@+id/shutDowntAlarm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="关闭闹钟"
/>
</LinearLayout>
13.handler的使用UseHandleMessageActivity.java
/**使用Handle和Message*/
public class UseHandleMessageActivity extends Activity{
private String TAG="UseHandleMessageActivity";
/**定义参数*/
protected final static int PROGRESS_END = -1;
private ProgressBar progressbar;// 进度条
protected static int progress;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.use_handleandmessage);
progressbar = (ProgressBar)findViewById(R.id.bar);
startProgressBar();
}
/**建立Handle*/
protected Handler handler = new Handler(){
public void handleMessage(Message msg){
switch (msg.what){
case PROGRESS_END:
Toast.makeText(UseHandleMessageActivity.this, "loading finished"
, Toast.LENGTH_LONG).show();
break;
default:
progressbar.setProgress(msg.what);
}
};
};
/**启动线程*/
private void startProgressBar(){
new Thread(){
public void run(){
while(progress <100){
try{
Thread.sleep(100);
countProgress();
progress ++;
Log.d(TAG,"Count"+progress);
}catch(InterruptedException e){
e.printStackTrace();
}
}
endProgress();
}
}.start();
}
private void countProgress(){
/**获取Message对象*/
Message msg = Message.obtain();
/**将用户自定义的信息code封装到Message对象中*/
msg.what = progress;
/**发送信息*/
handler.sendMessage(msg);
}
private void endProgress(){
Message msg = Message.obtain();
msg.what = PROGRESS_END;
handler.sendMessage(msg);
}
}
14.handler使用的布局文件:use_handleandmessage.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ProgressBar
android:id="@+id/bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
style="?android:attr/progressBarStyleHorizontal"/>
</LinearLayout>
15.使用异步加载功能UseAsyncTaskActivity.java
public class UseAsyncTaskActivity extends Activity{
/**创建参数*/
private Button button;
private TextView text;
/**创建Activity*/
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.use_async);
getWidget();
button.setOnClickListener(asnyc);
}
/**关联组件*/
private void getWidget(){
button = (Button) findViewById(R.id.button_async);
text = (TextView) findViewById(R.id.text_async);
}
/**创建监听*/
public Button.OnClickListener asnyc = new Button.OnClickListener(){
public void onClick(View view){
/**获取LoadTast对象*/
LoadTast loadtast = new LoadTast();
/**执行异步task*/
loadtast.execute();
}
};
/**继承自AsyncTast的LoadTast*/
public class LoadTast extends AsyncTask<Void, Integer, String>{
private ProgressDialog progressDialog;
protected String doInBackground(Void... params) {
/**模拟一个加速的进度*/
int sum = 1;
while(sum <= 100 ){
try{
Thread.sleep(100);
publishProgress(sum);
sum ++;
}catch(InterruptedException e){
e.printStackTrace();
}
}
return "Loading Finished..";
}
public void onPreExecute(){
/**创建一个对话框并显示*/
progressDialog = ProgressDialog.show(UseAsyncTaskActivity.this,
"AsyncTask Demo", "Loading....", true);
}
public void onProgressUpdate(Integer... values){
/**将从publishProgress传递过来的值进行格式化后显示到TextView组件*/
text.setText(values[0] +"%");
}
public void onPostExecute(String result){
/**隐藏对话框*/
progressDialog.dismiss();
/**将从onInBackground返回的result设置到TextView组件*/
text.setText(result);
}
};
}
16.使用异步加载功能的布局文件:use_async.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/button_async"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="启动普通服务"
/>
<TextView
android:id="@+id/text_async"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="加载"
/>
</LinearLayout>
</ScrollView>
17.获取手机状态信息UsePhoneStateActivity.java
/**获取手机的状态*/
public class UsePhoneStateActivity extends Activity{
private String TAG="UsePhoneStateActivity";
/**创建参数*/
private ContentResolver cr;
private Button getStateButton;// 用来获取用户的手机状态
/**创建Activity*/
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.usephonestate);
cr = getContentResolver();
Log.d(TAG,"cr = getContentResolver()");
getStateButton = (Button) findViewById(R.id.button_getphonestate);
getStateButton.setOnClickListener(getState);
}
private Button.OnClickListener getState = new Button.OnClickListener(){
public void onClick(View view){
/**获得TelephonyManager对象*/
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Service.TELEPHONY_SERVICE);
/**获取电信网络级别*/
String teleCode = telephonyManager.getNetworkCountryIso();
/**获取电信网络公司代码*/
String teleComCode = telephonyManager.getNetworkOperator();
/**获取电信网络公司名称*/
String teleComName = telephonyManager.getNetworkOperatorName();
/**获取行动通信类型*/
int TypeCode = telephonyManager.getPhoneType();
String type = "";
switch(TypeCode){
case TelephonyManager.PHONE_TYPE_NONE:
type = "PHONE_TYPE_NONE";
break;
case TelephonyManager.PHONE_TYPE_GSM:
type = "PHONE_TYPE_GSM";
break;
case TelephonyManager.PHONE_TYPE_CDMA:
type = "PHONE_TYPE_CDMA";
break;
}
/**获取网络类型*/
int netTypeCode = telephonyManager.getNetworkType();
String netType = "NETWORK_TYPE_UNKNOW";
switch(netTypeCode){
case TelephonyManager.NETWORK_TYPE_1xRTT:
netType = "NETWORK_TYPE_1xRTT";
break;
case TelephonyManager.NETWORK_TYPE_CDMA:
netType = "NETWORK_TYPE_CDMA";
break;
case TelephonyManager.NETWORK_TYPE_EDGE:
netType = "NETWORK_TYPE_EDGE";
break;
case TelephonyManager.NETWORK_TYPE_EVDO_0:
netType = "NETWORK_TYPE_EVDO_0";
break;
case TelephonyManager.NETWORK_TYPE_EVDO_A:
netType = "NETWORK_TYPE_EVDO_A";
break;
case TelephonyManager.NETWORK_TYPE_GPRS:
netType = "NETWORK_TYPE_GPRS";
break;
case TelephonyManager.NETWORK_TYPE_HSDPA:
netType = "NETWORK_TYPE_HSDPA";
break;
case TelephonyManager.NETWORK_TYPE_HSPA:
netType = "NETWORK_TYPE_HSPA";
break;
case TelephonyManager.NETWORK_TYPE_HSUPA:
netType = "NETWORK_TYPE_HSUPA";
break;
case TelephonyManager.NETWORK_TYPE_IDEN:
netType = "NETWORK_TYPE_IDEN";
break;
case TelephonyManager.NETWORK_TYPE_UMTS:
netType = "NETWORK_TYPE_UMTS";
break;
default:
break;
}
/**获取漫游状态*/
boolean roamStatusCode = telephonyManager.isNetworkRoaming();
String roamStatus = "NOT ROAMINF";
if(roamStatusCode){
roamStatus = "ROAMING";
}
/**获取手机唯一标识*/
String imei = telephonyManager.getDeviceId();
/**获取手机IMEI SV*/
String imeiSV = telephonyManager.getDeviceSoftwareVersion();
/**获取手机IMSI*/
String imsi = telephonyManager.getSubscriberId();
/**蓝牙服务*/
String statusCode = android.provider.Settings.System.getString(cr,
android.provider.Settings.System.BLUETOOTH_ON);
String bulettothStatus = "";
if(statusCode.equals("1")){
bulettothStatus = "ENABLE";
}else{
bulettothStatus = "DISABLE";
}
/**飞行模式是否打开*/
statusCode = android.provider.Settings.System.getString(cr,
android.provider.Settings.System.AIRPLANE_MODE_ON);
String AirplaneStatus = "";
if(statusCode.equals("1")){
AirplaneStatus = "ENABLE";
}else{
AirplaneStatus = "DISABLE";
}
/**数据漫游模式是否打开*/
statusCode = android.provider.Settings.System.getString(cr,
android.provider.Settings.System.DATA_ROAMING);
String dataRoamStatus = "";
if(statusCode.equals("1")){
dataRoamStatus = "ENABLE";
}else{
dataRoamStatus = "DISABLE";
}
TextView txt = (TextView) findViewById(R.id.text_showphonestate);
StringBuilder sb = new StringBuilder();
sb.append("teleCode: "+teleCode+"\n");
sb.append("teleComCode: "+teleComCode+"\n");
sb.append("teleComName: "+teleComName+"\n");
sb.append("type: "+type+"\n");
sb.append("netType: "+netType+"\n");
sb.append("roamStatus: "+roamStatus+"\n");
sb.append("imei: "+imei+"\n");
sb.append("imeiSV: "+imeiSV+"\n");
sb.append("imsi: "+imsi+"\n");
sb.append("bulettothStatus: "+bulettothStatus+"\n");
sb.append("AirplaneStatus: "+AirplaneStatus+"\n");
sb.append("dataRoamStatus: "+dataRoamStatus+"\n");
txt.setText(sb.toString());
}
};
}
18.获取手机状态信息的布局文件:usephonestate.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/button_getphonestate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="获取手机状态"
/>
<TextView
android:id="@+id/text_showphonestate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
</ScrollView>
19.拨打电话UseActionCallActivity.java
/**如何拨打电话*/
public class UseActionCallActivity extends Activity{
private String TAG="UseActionCallActivity";
/**创建参数*/
private Button call_Button;
private EditText etext_callnumber;
/**创建Activity*/
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.use_action_call);
getWidget();
call_Button.setOnClickListener(call_Phone);
}
//初始化控件
public void getWidget(){
call_Button = (Button) findViewById(R.id.button_call);
etext_callnumber = (EditText) findViewById(R.id.etext_action_call);
}
/**读取手机状态需要权限android.premission,CALL_PHONE*/
private Button.OnClickListener call_Phone= new Button.OnClickListener(){
public void onClick(View view){
String phoneNum = etext_callnumber.getText().toString().trim();
Log.d(TAG, phoneNum);
Uri uri = Uri.parse("tel:"+phoneNum);// 将电话号码解析为Uri
Intent intent = new Intent();
intent.setAction(Intent.ACTION_CALL);// 将intent的Action设为call
intent.setData(uri);// 将Uri对象传入intent对象
startActivity(intent);// 开始通话
}
};
}
20.拨打电话的布局文件:use_action_call.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/etext_action_call"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textCursorDrawable="@null"
android:text=""/>
<Button
android:id="@+id/button_call"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="拨号"
/>
</LinearLayout>
</ScrollView>
21.使用震动功能的实现:UseVibratorActivity.java
/**如何实现手机的震动提示Vibrator*/
public class UseVibratorActivity extends Activity{
private String TAG="UseVibratorActivity";
private Button vibrator_1_Button;
private Button vibrator_2_Button;
private Button vibrator_3_Button;
private Button stopVibratorBtn;
private Vibrator vibrator;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.use_vibrator);
vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
getWidget();
registerWidget();
}
//初始化控件
public void getWidget(){
vibrator_1_Button = (Button) findViewById(R.id.button_vibrator_1);
vibrator_2_Button = (Button) findViewById(R.id.button_vibrator_2);
vibrator_3_Button = (Button) findViewById(R.id.button_vibrator_3);
stopVibratorBtn =(Button) findViewById(R.id.stop_vibrator);
}
//注册监听
public void registerWidget(){
vibrator_1_Button.setOnClickListener(vibrator_1);
vibrator_2_Button.setOnClickListener(vibrator_2);
vibrator_3_Button.setOnClickListener(vibrator_3);
stopVibratorBtn.setOnClickListener(stopvibrator);
}
/**震动一次*/
public Button.OnClickListener vibrator_1 = new Button.OnClickListener(){
public void onClick(View view){
/**long参数数组里大参数的含义*/
/**第一个参数表示等待100毫秒后开始震动*/
/**第二个参数表示震动100毫秒后停止震动*/
vibrator.vibrate(new long[]{100,100}, 0);
}
};
/**震动两次*/
public Button.OnClickListener vibrator_2 = new Button.OnClickListener(){
public void onClick(View view){
vibrator.vibrate(new long[]{1000,3000,1000,3000}, 0);
}
};
/**震动三次*/
public Button.OnClickListener vibrator_3 = new Button.OnClickListener(){
public void onClick(View view){
vibrator.vibrate(new long[]{1000,1000,1000,2000,1000,300}, 0);
}
};
public Button.OnClickListener stopvibrator= new Button.OnClickListener(){
public void onClick(View view){
vibrator.cancel();
}
};
}
22.使用震动功能的布局文件:use_vibrator.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/button_vibrator_1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="震动一次"
/>
<Button
android:id="@+id/button_vibrator_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="震动两次"
/>
<Button
android:id="@+id/button_vibrator_3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="震动三次"
/>
<Button
android:id="@+id/stop_vibrator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="停止震动"
/>
</LinearLayout>
</ScrollView>
23.配置文件AndroidManifest.xml的权限添加与组件注册
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myservicedemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="Android服务的学习"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".UseBriderActivity"></activity>
<activity android:name=".UseBroadcastActivity"></activity>
<receiver android:name=".UseBroadcastReceiver">
<intent-filter>
<action android:name="com.example.myservicedemo" />
</intent-filter>
</receiver>
<activity android:name=".UseNotificationActivity"></activity>
<activity android:name=".UseAlarmManagerActivity"></activity>
<activity android:name=".UsePhoneStateActivity"></activity>
<activity android:name=".UseVibratorActivity"></activity>
<activity android:name=".UseActionCallActivity"></activity>
<activity android:name=".UseHandleMessageActivity"></activity>
<activity android:name=".UseAsyncTaskActivity"></activity>
<service android:name=".CountService"></service>
</application>
</manifest>