【ThreadPractice_android】实践是知识的母亲,知识是生活的明灯。这篇文章主要讲述ThreadPractice_android相关的知识,希望能为你提供帮助。
RandomService.java
public class RandomService extends Service {
private Thread workThread;
private static double random;
@Nullable
@Override
public android.os.IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
workThread = new Thread(null, workRunnable, "work");
Toast.makeText(this, "create()", Toast.LENGTH_LONG).show();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "start()", Toast.LENGTH_LONG).show();
if(!workThread.isAlive()){
workThread.start();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Destroy()", Toast.LENGTH_LONG).show();
}
Runnable workRunnable = new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()){
try{
random = Math.round(Math.random()*100);
MainActivity.updateGUI(random);
Thread.sleep(1000);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}
};
}
////////////////////////////////////////////////////////////////////////
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static TextView textView = null;
Button btn_start;
Button btn_stop;
private static Handler handler = new Handler();
private static double random;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.text);
btn_start = (Button)findViewById(R.id.btn_start);
btn_stop = (Button)findViewById(R.id.btn_stop);
final Intent intent = new Intent(this, RandomService.class);
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startService(intent);
}
});
btn_stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(intent);
}
});
}
public static void updateGUI(double _random){
random = _random;
handler.post(new Runnable() {
@Override
public void run() {
textView.setText(String.valueOf(random));
}
});
}
}
推荐阅读
- Android 里的数据储存
- ListViewPopMenuDBAdapter_android
- Android List,Set,Map集合安全 集合区别 并发集合类性能分析
- 5G时代,手机和App会有什么样的变化?
- 在 app 界面布局和静态页面编写之前需要了解的事
- Android 命名规范 (提高代码可以读性)
- Android 加载大图
- react create-react-app 怎么添加sass
- react create-react-app 跨域