事先準備
1. 你要在哪裡啟動Service
2. 你要在哪裡關閉Service
3. 準備一個class來繼承Service
Let's gooooooooooooooooooo...
這是啟動Service的方法
public void StartService(){ Intent intentService = new Intent(啟動Service的class.this, 繼承Service的class.class); intentService.setFlags(intentService.FLAG_ACTIVITY_NEW_TASK); startService(intentService); }
這是關閉Service的方法,一定要關閉哦,不然會一直做Service的事情
public void StopService(){ Intent intentService = new Intent(關閉Service的class.this, 繼承Service的class.class); stopService(intentService); }
燈燈燈燈......重點來了=>繼承Service的class
public class ServiceActivity extends Service{ private Handler objhandler = new Handler(); //I want to debug start Service or not private int intCounter=0; private Runnable mTasks = new Runnable() { public void run() { //每次進來就+1 可以檢查有沒有正常執行 intCounter +=1; Log.i("Ken", "Counter:" + Integer.toString(intCounter)); //every 5 sec to run this task objhandler.postDelayed(mTasks, 5000); } }; public void onStart(Intent intent, int startId) { super.onStart(intent, startId); }; @Override public void onCreate() { objhandler.postDelayed(mTasks, 5000); super.onCreate(); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onDestroy() { objhandler.removeCallbacks(mTasks); super.onDestroy(); } }
再來這個AndroidManifest.xml一定也要加入哦,不然Android不認識妳
在這三項外面記得包成
<service
android:name=".ServiceActivity"
android:exported="true"
android:process=":remote">
</service>
AndroidManifest.xml android:exported="true" android:name=".ServiceActivity" android:process=":remote;
這樣就大功告成了OHYA.................
沒有留言:
張貼留言