Service 將自己本身關閉
AndroidManifest.xml 註冊 Service 標籤
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ceph.monitor.service">
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
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>
<service android:name=".MainService" />
</application>
</manifest>
MainActivity.java
public class MainActivity extends Activity {
Activity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
Intent intent = new Intent(activity, MainService.class);
startService(intent);
}
}
MainService.java
public class MainService extends Service {
private int count;
private Timer timer;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
count = 0;
TimerTask action = new TimerTask() {
@Override
public void run() {
if (count < 3) {
Log.d("MainService", "次數: " + count);
count = count + 1;
} else {
Log.d("MainService", "結束背景服務。");
timer.cancel();
stopSelf();
}
}
};
timer = new Timer();
timer.schedule(action, 1000, 1000);
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}