1. 程式人生 > >一個Demo學完Android中所有的服務

一個Demo學完Android中所有的服務

               

注:這個例子來自“安卓巴士”,經閱讀,理解,寫此文章

說明:這個例子實現了Android中常見的許多服務,下面是實現的截圖

接下來,以原始碼的方式分析這個例子

1.MainActivity--主介面

這個類主要是實現使用者所看到的這個Activity,其中包含了一系列的按鈕,使用者點選按鈕執行相應的動作,所以在這個類中主要是對按鈕的定義和對按鈕繫結相應的監聽器,下面是實現的程式碼:

package lovefang.stadyService;import android.app.Activity;import android.os.Bundle;import android.widget.Button;import
android.view.View;import android.content.Intent;import android.util.Log;/**這是使用後臺服務的學習例子*/public class MainStadyServics extends Activity {     /**引數設定*/ 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.v("MainStadyServics"
, "setContentView");        setContentView(R.layout.main);        getWidget();        regiestListener();    }     /**獲得元件*/    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 regiestListener(){     startServiceButton.setOnClickListener(startService);     shutDownServiceButton.setOnClickListener(shutdownService);     startBindServiceButton.setOnClickListener(startBinderService);     sendBroadcast.setOnClickListener(broadcastReceiver);     notificationButton.setOnClickListener(notification);     alarmButton.setOnClickListener(startAlarm);     handlerButton.setOnClickListener(handler);     asyncButton.setOnClickListener(async);     phoneStateButton.setOnClickListener(phonestate);     callphoneButton.setOnClickListener(callphoneEvent);     vibratorButton.setOnClickListener(vibrator);    }     /**啟動服務的事件監聽*/    public Button.OnClickListener startService = new Button.OnClickListener(){     public void onClick(View view){       /**單擊按鈕時啟動服務*/      Intent intent = new Intent(MainStadyServics.this,CountService.class);      startService(intent);      Log.v("MainStadyServics", "start Service");     }    };     /**關閉服務*/    public Button.OnClickListener shutdownService = new Button.OnClickListener(){     public void onClick(View view){       /**單擊按鈕時啟動服務*/      Intent intent = new Intent(MainStadyServics.this,CountService.class);       /**退出Activity是,停止服務*/      stopService(intent);      Log.v("MainStadyServics", "shutDown serveice");     }    };     /**開啟繫結服務的Activity*/    public Button.OnClickListener startBinderService = new Button.OnClickListener(){     public void onClick(View view){       /**單擊按鈕時啟動服務*/      Intent intent = new Intent(MainStadyServics.this,UseBrider.class);      startActivity(intent);      Log.v("MainStadyServics", "start Binder Service");     }    };     /**開啟廣播學習的按鈕*/    public Button.OnClickListener broadcastReceiver = new Button.OnClickListener(){     public void onClick(View view){      Intent intent = new Intent(MainStadyServics.this,UseBroadcast.class);      startActivity(intent);      Log.v("MainStadyServics","start broadcast");     }    };     /**開啟通知*/    public Button.OnClickListener notification = new Button.OnClickListener(){     public void onClick(View view){      Intent intent = new Intent(MainStadyServics.this, UseNotification.class);      startActivity(intent);      Log.v("MainStadyService ","start Notification");           }    };     /**使用鬧鐘*/    public Button.OnClickListener startAlarm = new Button.OnClickListener(){     public void onClick(View view){      Intent intent = new Intent(MainStadyServics.this, UseAlarmManager.class);      startActivity(intent);      Log.v("MainStadyService ","start alarm");           }    };    public Button.OnClickListener handler= new Button.OnClickListener(){     public void onClick(View view){      Intent intent = new Intent(MainStadyServics.this, UseHandleMessage.class);      startActivity(intent);      Log.v("MainStadyService ","start handle");     }    };    public Button.OnClickListener async= new Button.OnClickListener(){     public void onClick(View view){      Intent intent = new Intent(MainStadyServics.this, UseAsyncTask.class);      startActivity(intent);      Log.v("MainStadyService ","start handle");     }    };    public Button.OnClickListener phonestate= new Button.OnClickListener(){     public void onClick(View view){      Intent intent = new Intent(MainStadyServics.this, UsePhoneState.class);      startActivity(intent);      Log.v("MainStadyService ","start phonestate");     }    };    public Button.OnClickListener callphoneEvent= new Button.OnClickListener(){     public void onClick(View view){      Intent intent = new Intent(MainStadyServics.this, UseActionCall.class);      startActivity(intent);      Log.v("MainStadyService ","start callphone");     }    };    public Button.OnClickListener vibrator= new Button.OnClickListener(){     public void onClick(View view){      Intent intent = new Intent(MainStadyServics.this, UseVibrator.class);      startActivity(intent);      Log.v("MainStadyService ","start callphone");     }    };     /***/    protected void onDestroy(){     super.onDestroy();     Intent intent = new Intent(MainStadyServics.this,CountService.class);      /**退出Activity是,停止服務*/     stopService(intent);    }         }
2.啟動服務按鈕

這個類實現的是第一個按鈕的功能,在這個類中新開了一個執行緒,並每隔一秒打印出一行日誌

程式碼如下:

package lovefang.stadyService;/**引入包*/ import android.app.Service;// 服務的類 import android.os.IBinder; import android.os.Binder; import android.content.Intent; import android.util.Log;/**計數的服務*/ public class CountService extends Service{   /**建立引數*/  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.v("CountService","Count is"+count);     }    }   }).start();  }  public void onDestroy(){   super.onDestroy();    /**服務停止時,終止計數程序*/   this.threadDisable = true;  }  public int getConunt(){   return count;  }  class ServiceBinder extends Binder{   public CountService getService(){    return CountService.this;   }  } }
3.繫結服務

服務有兩種實現的方法:

1.startService,啟動服務,這時需要程式設計師管理服務的生命週期

2.bindService,繫結服務,此時Service與Activity繫結在一起

下面是實現的程式碼:

package lovefang.stadyService;/**引入包*/ import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log;/**通過bindService和unBindSerivce的方式啟動和結束服務*/ public class UseBrider extends Activity {   /**引數設定*/  CountService countService;   @Override  public void onCreate(Bundle savedInstanceState) {      super.onCreate(savedInstanceState);      setContentView(new UseBriderFace(this));      Intent intent = new Intent(UseBrider.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.v("MainStadyServics", "out");  } }
4.傳送廣播

使用sendBroadcast,向一個Action傳送廣播,並由相應的廣播接收器接收並執行相應的動作

實現的程式碼如下:

4.1 開啟廣播服務

package lovefang.stadyService;/**引入包*/ import android.view.View; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.widget.Button;/**使用Broadcast,這是一個傳送廣播的類*/ public class UseBroadcast extends Activity{   /**建立引數*/  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 Braodcast demo");// 設定廣播的內容    intent.setAction("lovefang.stadyService");// 設定廣播的Action    sendBroadcast(intent);   }  };   }

4.2 處理廣播訊息

package lovefang.stadyService;/***/ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log;/**這是一個接收廣播的類*/ public class UseBroadcastReceiver extends BroadcastReceiver{  public void onReceive(Context context, Intent intent){   Log.v("UseBroadcastReceiver", "I get a message");  } }
5.Notification

這個稱之為通知,顯示在手機的通知欄,使用者可以清除,可以點選

實現的程式碼如下:

package lovefang.stadyService; import android.content.Intent; import android.os.Bundle; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.net.Uri; import android.media.RingtoneManager; import android.widget.Button; import android.view.View;/**使用notification*/ public class UseNotification 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(UseNotification.this,       0, new Intent(UseNotification.this,UseNotification.class)       , 0);     /**設定通知訊息*/    notification.setLatestEventInfo(UseNotification.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(      UseNotification.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);// 關閉通知   }  }; }
6.Alarm

鬧鐘服務

package lovefang.stadyService;import android.app.Activity;import android.os.Bundle;import android.widget.Button;import android.view.View;import android.app.AlarmManager;import java.util.Calendar;public class UseAlarmManager 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);  } };}
7.獲取手機的狀態

這個功能實現的是獲取使用者手機的一些定義的資訊

package lovefang.stadyService;/**引入包*/ import android.os.Bundle; import android.app.Activity; import android.app.Service; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.content.ContentResolver;//This class provides applications access to the content model. import android.telephony.TelephonyManager; import android.util.Log;/**獲取手機的狀態*/ public class UsePhoneState extends Activity{   /**建立引數*/  private ContentResolver cr;  private Button getStateButton;// 用來獲取使用者的手機狀態   /**建立Activity*/  public void onCreate(Bundle savedInstanceState){   super.onCreate(savedInstanceState);   setContentView(R.layout.usephonestate);      cr = getContentResolver();   Log.v("UsePhonestate","cr = getContentResolver()");   Log.v("UsePhonestate","setContentView");   getStateButton = (Button) findViewById(R.id.button_getphonestate);   Log.v("UsePhonestate","getStateButton");   getStateButton.setOnClickListener(getState);   Log.v("UsePhonestate","getStateButton.setOnClickListener");  }  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());   }  }; }
8.Vibrator

震動功能,實現對手機震動的管理

package lovefang.stadyService;/***/ import android.os.Bundle; import android.os.Vibrator; import android.app.Activity; import android.view.View; import android.content.Context; import android.widget.Button;/**如何實現手機的震動提示Vibrator*/ public class UseVibrator extends Activity{   /***/  private Button vibrator_1_Button;  private Button vibrator_2_Button;  private Button vibrator_3_Button;  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);  }    public void registerWidget(){   vibrator_1_Button.setOnClickListener(vibrator_1);   vibrator_2_Button.setOnClickListener(vibrator_2);   vibrator_3_Button.setOnClickListener(vibrator_3);  }   /**震動一次*/  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);   }  }; }

下面給出原始碼的下載地址: