サービス初歩
3104 ワード
例:
ServiceActivity.class
FirstService.class
AndroidManifest.xml
PS:バージョンandroid 2になったら.1以上、onStartメソッドの代わりにonStartCommandメソッドを使用します.
ServiceActivity.class
public class ServiceActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(ServiceActivity.this, FirstService.class);
startService(i);
}
});
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(ServiceActivity.this, FirstService.class);
stopService(i);
}
});
}
}
FirstService.class
public class FirstService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("service onBind");
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
System.out.println("service onCreate");
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("service onDestroy");
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
System.out.println("service onStart");
System.out.println("startId:"+startId);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cn"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ServiceActivity"
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=".FirstService"></service>
</application>
</manifest>
PS:バージョンandroid 2になったら.1以上、onStartメソッドの代わりにonStartCommandメソッドを使用します.