MainActivity
package com.jing.example.nknu_.android_service_lifecycle;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button button;
private Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)this.findViewById(R.id.button);
button2 = (Button)this.findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,HelloService.class);
intent.putExtra("name","jack");
startService(intent);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,HelloService.class);
//Service銷毀,用於播放器關閉
stopService(intent);
}
});
}
}
HelloService
package com.jing.example.nknu_.android_service_lifecycle;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
/**
* Created by nknu_ on 2016/3/5.
* 修正 2016/3/15
*/
public class HelloService extends Service {
private final String TAG = "HelloService";
public HelloService(){
}
@Override
public void onCreate() {//目前在此無作用
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String name = intent.getStringExtra("name");
System.out.println("--HelloService's onStartCommand->>" + name);
//Service 銷毀,用於程式內部本身
//stopSelf();
return super.onStartCommand(intent, flags, startId);
}
public void onDestroy(){
System.out.println( "--HelloService's onDestroy->>");
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {//目前在此無作用,但必須設定
return null;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jing.example.nknu_.android_service_lifecycle">
<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-->
<service android:name=".HelloService"></service>
</application>
</manifest>