1 写Activity【实例是打印当前的时间】
1) 容易错的地方
是
startService
而不是
startActivity
package com.mingrisoft;
import android.app.IntentService;
import android.content.Intent;
import android.text.format.Time;
import android.util.Log;
public class AndServer extends IntentService{
public AndServer() {
super("设置一下当前时间的服务");
}
@Override
protected void onHandleIntent(Intent intent) {
Time time = new Time();
time.setToNow();
String timesString = time.format("%Y-%m-%d %H:%M:%S");
Log.i("std", timesString);
}
}
package com.mingrisoft;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
/**
* Demonstration of using fragments to implement different activity layouts.
* This sample provides a different layout (and activity flow) when run in
* landscape.
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // 设置该Activity使用的布局
ImageView iv=(ImageView)findViewById(R.id.imageButton0);
iv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "正准备进入游戏...", Toast.LENGTH_SHORT).show();
startService(new Intent(MainActivity.this,AndServer.class));
// startActivity(new Intent(MainActivity.this,CurrentTimeService.class));
// startService(new Intent(MainActivity.this, CurrentTimeService.class));// 启动服务
}
});
}
}
2一个IntentService类
package com.mingrisoft;
import android.app.IntentService;
import android.content.Intent;
import android.text.format.Time;
import android.util.Log;
public class AndServer extends IntentService{
public AndServer() {
super("设置一下当前时间的服务");
}
@Override
protected void onHandleIntent(Intent intent) {
Time time = new Time();
time.setToNow();
String timesString = time.format("%Y-%m-%d %H:%M:%S");
Log.i("std", timesString);
}
}
需要注意 构造方法重写用不带参数的
3 在 配置文件加上
<service android:name=".AndServer" >
</service>
4 结果
5 还可以是用Service,都类似,Service主题类如下,结果还是一样的
package com.mingrisoft;
import android.app.IntentService;
import android.content.Intent;
import android.text.format.Time;
import android.util.Log;
public class AndServer extends IntentService{
public AndServer() {
super("设置一下当前时间的服务");
}
@Override
protected void onHandleIntent(Intent intent) {
Time time = new Time();
time.setToNow();
String timesString = time.format("%Y-%m-%d %H:%M:%S");
Log.i("std", timesString);
}
}