幾乎在全部平臺上都有不少進程運行背景,它們被稱爲服務。可能在Android平臺中有一些服務能夠執行長時間運行的操做,這些操做在處理時不須要用戶交互。 java
在本文中,藉助預約義的Android警報服務,咱們將建立一個應用程序,在所需的時間間隔內將電話模式更改成振動模式。除此以外,咱們將編寫本身的Service類並在特定時間調用它。此外,此演示應用程序將回答如下問題:android
要理解本文,讀者應該瞭解Java和Android平臺。git
在開始編碼以前,應用程序的結構應該在編碼器的腦海中清楚。對於此演示應用程序,咱們能夠按照如下簡單步驟操做:app
MainActivity
BroadcastReceivers
以接收警報並執行操做或呼叫服務。在這個演示中,有4個類:ide
MainActivity // main calss FromHourAlarmReceiver //BroadcastReceiver ToHourAlarmReceiver //BroadcastReceiver MyService //Service Class
public class MainActivity extends Activity { private EditText editText1; //create the objects private EditText editText2; private Button btn1; private int hourFrom; private int hourTo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); editText1 = (EditText) findViewById(R.id.editText1); //bind the object editText2 = (EditText) findViewById(R.id.editText2); btn1 = (Button) findViewById(R.id.btn1); btn1.setOnClickListener(new OnClickListener() { //click listener for btn @Override public void onClick(View v) { }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter The Desired Time Interval For To Changed In Vibrate Mode" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="From (24 Hour Format)" /> <EditText android:id="@+id/editText1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:numeric="integer" /> <TextView