Android開發零點起飛(第七章)筆記-單純Android執行Service執行計數只能在Log看到變化
Android開發零點起飛(第七章)筆記-單純Android執行Service執行計數只能在Log看到變化
//CountService.java
package com.example.jashsample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class CountService extends Service {
private boolean threadDisable;
private int count;
@Override
public IBinder onBind(Intent intent) {
return null ;
}
@Override
public void onCreate() {
super.onCreate();
new Thread( new Runnable() {
@Override
public void run() {
while ( ! threadDisable) {
try {
Thread.sleep( 1000 );
} catch (InterruptedException e) {
}
count ++ ;
Log.v( " CountService " , " Count is " + count);
}
}
}).start();
}
@Override
public void onDestroy() {
super .onDestroy();
this .threadDisable = true ;
Log.v( " CountService " , " on destroy " );
}
public int getCount() {
return count;
}
}
//MainActivity.java
package com.example.jashsample;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
/*
00.目的新增一個有Service功能的範例
01.新增CountService
02.在設定檔新增<service android:name ="CountService" />
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this .startService( new Intent( this , CountService. class ));
}
@Override
protected void onDestroy() {
super .onDestroy();
this .stopService( new Intent( this , CountService. class ));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
//AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.jashsample" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name="com.example.jashsample.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="CountService"/> </application> </manifest>