文章的思路就是在主线程中设置一个按钮,启动一个线程,在子线程中进行线程的耗时操作,最后需要记住添加蓝牙权限
AndroidManifest.xml中加入
package com.example.testcamera;
import java.io.IOException;
import android.R.anim;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button startButton;
TextView textView;
Handler handle = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
textView.setText(" "+msg.arg1);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton=(Button) findViewById(R.id.startButton);
textView=(TextView) findViewById(R.id.tv);
startButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
MyThread myThread=new MyThread();
myThread.start();
}
});
}
class MyThread extends Thread {
@Override
public void run() {
// 耗时操作
int num=0;
while(true){
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
.getDefaultAdapter();
mBluetoothAdapter.disable();//关闭蓝牙
String string1=mBluetoothAdapter.getAddress();
Log.e("test", "关闭"+mBluetoothAdapter.getState());
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mBluetoothAdapter.enable();
String string=mBluetoothAdapter.getAddress();
Message msg = new Message();
num++;
msg.arg1=num;
Log.e("bluetest", "开启"+mBluetoothAdapter.getState());
Log.e("bluetest", string);
Log.e("bluetest","总的次数"+num);
handle.sendMessage(msg);
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.run();
}
}
}
}
这里我在主界面更新开关的次数,也将开关的状态的返回值,打开的返回值,蓝牙的mac地址,和开关的次数输出到了log之中。
这里,谢谢我同事b.z对我的提醒