Android SERVICE(详解一)
--------------.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView1"
android:layout_alignRight="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button" />
</RelativeLayout>
--------------------.java
package com.example.service1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends
Activity {
@Override
public void onCreate(
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("MainActivity", "in");
findViewById(R.id.button1)
.setOnClickListener(
new OnClickListener() {
public void onClick(
View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(
MainActivity.this,
New.class);
startService(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(
Menu menu) {
getMenuInflater().inflate(
R.menu.activity_main,
menu);
return true;
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Intent intent = new Intent(
MainActivity.this,
New.class);
stopService(intent);
Log.v("MainActivity", "out");
}
}
--------------------.java2
package com.example.service1;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class New extends Service{
boolean Disable;
int count;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
while (!Disable) {
try {
Thread.sleep(1000);
}
catch (Exception e) {
// TODO: handle exception
}
count++;
Log.v("Service", "总数"+count);
}
}
}).start();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
this.Disable=true;
}
}
----------------------manifest加上
service
