<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="start"
android:text="开启服务"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="stop"
android:text="停止服务"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="call"
android:text="调用服务里面的方法"/>
</LinearLayout>
主Activity:
package com.sql.sericelife;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View v){
Intent intent = new Intent(this,MyService.class);
startService(intent);//通知框架开启服务
}
public void stop(View v){
Intent intent = new Intent(this,MyService.class);
stopService(intent);//通知框架停止服务
}
//调用服务里面的方法。不可以自己new服务,调用的服务的方法,必须通过框架得到服务的引用。
public void call(View view){
}
@Override
protected void onDestroy() {
System.out.println("啊啊啊,我是activity,我挂了");
super.onDestroy();
}
}
服务类:
package com.sql.sericelife;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service{
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 开启后服务后,此方法只调用一次
* */
@Override
public void onCreate() {
System.out.println("oncrete");
super.onCreate();
}
/**
* 每次调用服务,都会执行的方法
* */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
System.out.println("onstart");
return super.onStartCommand(intent, flags, startId);
}
/**
* 销毁服务执行的方法
* */
@Override
public void onDestroy() {
System.out.println("ondestory");
super.onDestroy();
}
/**
* 这是服务里面的一个方法
*/
public void methodInService(){
Toast.makeText(this, "哈哈,服务中自定义的方法", 0).show();
}
}
清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sql.sericelife"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<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="com.sql.sericelife.MyService"></service>
</application>
</manifest>
标签:生命周期,服务,void,start,Intent,import,android,public,layout From: https://blog.51cto.com/u_15955675/6040201