準備
1. こちらを参照して、Test1Service を追加します。
デザイン
1. main.xml にボタン (button1) を配置します。
サンプルコード (Java) - main アクティビティ
// import の追加
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.content.*;
import android.view.View;
import android.view.View.OnClickListener;
// コード
public class Test1Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Intent intent = new Intent(this, Test1Service.class);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
startService(intent);
}
});
Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
stopService(intent);
}
});
}
}
サンプルコード (Java) - Test1Service サービス
// import の追加
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
// コード
public class Test1Service extends Service {
NotificationManager NotifMan;
@Override
public void onCreate() {
super.onCreate();
NotifMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notif = new Notification(R.drawable.ic_launcher, "Hello", 0);
Intent it = new Intent(this, Test1Activity.class);
PendingIntent pit = PendingIntent.getActivity(this, 0, it, 0);
notif.setLatestEventInfo(this, "Hello", "Hanako Yamada", pit);
NotifMan.notify(0, notif);
}
@Override
public void onStart(Intent it, int id) {
super.onStart(it, id);
}
@Override
public void onDestroy(){
super.onDestroy();
NotifMan.cancel(0);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
解説
INTENT を使用して、main アクティビティから Test1Service サービスを起動します。


