1、在service中实现随机数产生;
2、实现Service中的各个生命周期函数,并理解其功能;
2、在Activity界面实现随机数的显示,每2秒更新一次;
3、采用启动式完成service的启动;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="TextView" />
<Button
android:id="@+id/start"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="startService"
android:text="startService"
/>
<Button
android:id="@+id/stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="stopService"
android:text="stopService"
/>
</LinearLayout>
MainActivity
package com.example.myapplication22;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.content.Intent;
import android.os.IBinder;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView txt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = findViewById(R.id.txt);
}
private Handler mHandler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
txt.setText(String.valueOf(Math.random()*100));
mHandler.postDelayed(this, 2000);
}
};
Thread thread = new Thread(runnable);
public void startService(View view) {
startService(new Intent(getBaseContext(), MyServiceToStart.class));
thread.start();
}
public void stopService(View view) {
mHandler.removeCallbacks(runnable);
stopService(new Intent(getBaseContext(), MyServiceToStart.class));
}
}
MyServiceToStart
package com.example.myapplication22;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyServiceToStart extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "服务已经启动", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "服务已经停止", Toast.LENGTH_LONG).show();
}
}