MainActivity.java
package com.jing.example.nknu_.p183_service;
/*
* 2016/3/15
* 作者:川匠神樂
* 功能:最基本的創造Service以及銷毀Service
*/
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, EatService.class);
startService(intent);
}
@Override
protected void onDestroy() {
Intent intent = new Intent(this,EatService.class);
stopService(intent);//銷毀Service
super.onDestroy();
}
}
EatService.java
package com.jing.example.nknu_.p183_service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* Created by nknu_ on 2016/3/15.
*/
public class EatService extends Service {
@Override
public void onCreate() {//初始化介面
super.onCreate();
System.out.println("進入EatService的onCreate");
}
@Override
public void onDestroy() {//清理使用的資源
System.out.println("進入EatService的onDestroy");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {//回傳溝通介面
System.out.println("進入EatService的onBind");
return null;
}
}
AndroidManifext.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jing.example.nknu_.p183_service">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--Service需在</activity>之下作申請-->
<service android:name="com.jing.example.nknu_.p183_service.EatService"></service>
</application>
</manifest>