Android實現開機自啟動Service

來源:互聯網
上載者:User

一、首先做一個監聽器:

public class StartBroadcastReceiver extends BroadcastReceiver{<br />private static final String ACTION = "android.intent.action.BOOT_COMPLETED";<br />public void onReceive(Context context, Intent intent) {<br /> if (intent.getAction().equals(ACTION)){<br /> Intent i= new Intent(Intent.ACTION_RUN);<br /> i.setClass(context, TService.class);<br /> context.startService(i);<br /> }<br /> }</p><p>}

 

二、然後再做一個service:

package com.testService;<br />import android.app.Notification;<br />import android.app.NotificationManager;<br />import android.app.PendingIntent;<br />import android.app.Service;<br />import android.content.Intent;<br />import android.os.Binder;<br />import android.os.Handler;<br />import android.os.IBinder;<br />import android.util.Log;<br />public class TService extends Service {<br /> /**<br /> * 建立Handler對象,作為進程傳遞postDelayed之用<br /> */<br /> private Handler objHandler = new Handler();<br /> private int intCounter = 0;<br /> private static final String TAG = "TService";<br /> private NotificationManager notificationManager;<br /> private Runnable mTasks = new Runnable() {<br /> public void run() {<br /> intCounter++;<br /> Log.i("HIPPO", "Counter:" + Integer.toString(intCounter));<br /> objHandler.postDelayed(mTasks, 1000);<br /> }<br /> };<br /> public void onCreate() {<br /> Log.d(TAG, "============> TService.onCreate");<br /> notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);<br /> showNotification();<br /> super.onCreate();<br /> }</p><p> public void onStart(Intent intent, int startId) {<br /> Log.i(TAG, "============> TService.onStart");<br /> objHandler.postDelayed(mTasks, 1000);<br /> super.onStart(intent, startId);<br /> }<br /> public IBinder onBind(Intent intent) {<br /> Log.i(TAG, "============> TService.onBind");<br /> return null;<br /> }<br /> public class LocalBinder extends Binder {<br /> public TService getService() {<br /> return TService.this;<br /> }<br /> }<br /> public boolean onUnbind(Intent intent) {<br /> Log.i(TAG, "============> TService.onUnbind");<br /> return false;<br /> }<br /> public void onRebind(Intent intent) {<br /> Log.i(TAG, "============> TService.onRebind");<br /> }<br /> public void onDestroy() {<br /> Log.i(TAG, "============> TService.onDestroy");<br /> notificationManager.cancel(R.string.service_start);<br /> objHandler.removeCallbacks(mTasks);<br /> super.onDestroy();<br /> }<br /> private void showNotification() {<br /> Notification notification = new Notification(R.drawable.icon,<br /> "SERVICE START", System.currentTimeMillis());<br /> Intent intent = new Intent(this, testService.class);<br /> intent.putExtra("FLG", 1);<br /> PendingIntent contentIntent = PendingIntent.getActivity(this, 0,<br /> intent, 0);<br /> notification.setLatestEventInfo(this, "SERVICE", "SERVICE START",<br /> contentIntent);<br /> notificationManager.notify(R.string.service_start, notification);<br /> }<br />}

 

三、再做一個主程式:

package com.testService;<br />import android.app.Activity;<br />import android.content.Context;<br />import android.content.Intent;<br />import android.os.Bundle;<br />import android.view.View;<br />import android.view.View.OnClickListener;<br />import android.widget.Button;<br />import android.widget.Toast;<br />public class testService extends Activity {</p><p> private Button button01;<br /> private Button button02;<br /> private int flg;<br /> private Intent tsIntent;<br /> /** Called when the activity is first created. */<br /> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);</p><p> setContentView(R.layout.main);<br /> button01 = (Button)findViewById(R.id.Button01);<br /> button02 = (Button)findViewById(R.id.Button02);</p><p> tsIntent = this.getIntent();<br /> Bundle bundle = tsIntent.getExtras();</p><p> if (bundle == null){<br /> flg = 1;<br /> DisplayToast(this,"Service Start",2);<br /> startService();<br /> finish();<br /> }else{<br /> DisplayToast(this,"Service Stop",2);<br /> stopService();<br /> finish();<br /> }</p><p> button01.setOnClickListener(Listener01);<br /> button02.setOnClickListener(Listener02);</p><p> }</p><p> Button.OnClickListener Listener01 = new OnClickListener(){<br /> @Override<br /> public void onClick(View v) {<br /> // TODO Auto-generated method stub<br /> startService();<br /> }</p><p> };</p><p> Button.OnClickListener Listener02 = new OnClickListener(){<br /> @Override<br /> public void onClick(View v) {<br /> // TODO Auto-generated method stub<br /> stopService();<br /> }</p><p> };</p><p> private void startService() {<br /> Intent i = new Intent(testService.this, TService.class);<br /> i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<br /> this.startService(i);<br /> }</p><p> private void stopService() {<br /> Intent i = new Intent(testService.this, TService.class);<br /> this.stopService(i);<br /> }<br /> public static void DisplayToast(Context context , String str , int time){<br /> if (time == 1){<br /> //短時間顯示Toast<br /> Toast.makeText(context, str, Toast.LENGTH_SHORT).show();<br /> }else if (time == 2){<br /> //長時間顯示Toast<br /> Toast.makeText(context, str, Toast.LENGTH_LONG).show();<br /> }<br /> }<br />}

 

四、最後在androidmenfest.xml中註冊一下接受廣播器和服務以及開通許可權:

1、接收廣播器:

<receiver android:name=".StartBroadcastReceiver"><br /> <intent-filter><br /> <action android:name="android.intent.action.BOOT_COMPLETED"/><br /> </intent-filter><br /> </receiver>

 

2、服務:

<service android:name=".TService"<br /> android:label="TService"<br /> android:icon="@drawable/icon"<br /> android:enabled="true"<br /> android:exported="true"<br /> android:process=":remote"><br /> </service>

 

3、註冊許可權:

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

 

注意:接受廣播和服務都必須註冊在:<application>這裡註冊</application>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.