今日の一言
2012/06/09(Sat) ガーリックトーストのうまさは異常 [長年日記] 21:00現在曇 23℃
_ [Android][Java]AndroidでServiceを使う際のサンプル
以下に、ランチャーからアプリを起動するとServiceを自動で起動し、通知領域に情報を出すアプリのサンプルを示す。
起動したサービスはアプリのボタンを押すことでStart、Stopを切り替えることが出来る。
なお、サービスを起動したままアプリを閉じてしまったときのために、通知領域に出したメッセージをクリックすると、サービスを起動したアプリを再度呼び出すことができるようにした。
また、ブラウザからの起動用にIntentFilterを設定するため、ブラウザから以下のURLのリンクをクリックすることで、アプリを起動してサービスを実行できるようになっている。
( testapp://service/ )
【TestAppActivity.java】
package net.i.akihiro.TestApp;
import net.i.akihiro.TestApp.R.id;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class TestAppActivity extends Activity {
private static final String LOG_TAG = "TestApp";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
android.util.Log.println(Log.DEBUG, LOG_TAG, "--> " + this.getClass().getName() + " onCreate().");
setContentView(R.layout.main);
Uri uri = getIntent().getData();
if( uri != null )
{
String uriString = uri.toString();
android.util.Log.println(Log.DEBUG, LOG_TAG, uriString );
}
//start service button
Button button = (Button) findViewById(id.button);
button.setOnClickListener(new View.OnClickListener() {
boolean isRunning = true;
@Override
public void onClick(View v) {
Button button = (Button)v;
Intent intent = new Intent(TestAppActivity.this, TestAppServerService.class);
if( isRunning == false )
{
button.setText("Stop Service");
startService(intent);
}
else
{
button.setText("Start Service");
stopService(intent);
}
isRunning = !isRunning;
}
});
//startService
Intent intent = new Intent(TestAppActivity.this, TestAppServerService.class);
startService(intent);
button.setText("Stop Service");
}
}
【TestAppServerService.java】
package net.i.akihiro.TestApp;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class TestAppServerService extends Service {
private static final String LOG_TAG = "TestApp";
private NotificationManager mNotification;
int NOTIFICATION_ID = 0;
private Intent mSelfIntent = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "create service", Toast.LENGTH_SHORT).show();
mNotification = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
android.util.Log.println(Log.DEBUG, LOG_TAG, "create service");
}
@Override
public void onStart(Intent intent, int StartId) {
mSelfIntent = intent;
String message = intent.getStringExtra("Message");
if( message != null )
{
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
try{
// notification
Notification notification = new Notification(android.R.drawable.btn_default, "TestApp", System.currentTimeMillis());
notification.flags = Notification.FLAG_ONGOING_EVENT;
// intent
Intent targetIntent = new Intent(this, TestAppActivity.class);
// pending intent
PendingIntent pIntent = PendingIntent.getActivity(this, 0, targetIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
notification.setLatestEventInfo(this, "title", "message", pIntent);
mNotification.notify(NOTIFICATION_ID, notification);
} catch (Exception e) {
e.printStackTrace();
}
}
public void postExecute( String uniqueId )
{
stopSelf();
stopService(mSelfIntent);
mNotification.cancel(NOTIFICATION_ID);
}
@Override
public void onDestroy() {
mNotification.cancel(NOTIFICATION_ID);
Toast.makeText(this, "destroy service", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
}
【main.xml】
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="StartServer" />
</LinearLayout>
【AndroidManifest.xml】
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.i.akihiro.TestApp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="7" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:name=".TestAppApplication"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity android:name=".TestAppActivity" android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="testapp" android:host="service" android:pathPattern="/.*"/>
</intent-filter>
</activity>
<service android:name=".TestAppServerService">
</service>
</application>
</manifest>
[TrackBack URL: http://akihiro-i.net/~akihiro-i/diary/tb.rb/20120609]