【发布时间】:2015-08-24 16:02:35
【问题描述】:
所以我尝试在 Android 应用程序中提供服务,这是我在 android 上的第一个应用程序(也是在 Java 上),所以我有很多问题。但主要问题是“架构”我的后台服务。
我需要通过蓝牙设置与设备(我的自定义设备)的连接。我有自己的协议(仍在进行中),因此我的后台服务需要以下内容:
- 发送了一些东西
- 始终收听 InputStream! (一直)
如何在我的服务中创建这个? 我需要在我的服务中创建两个线程?
我已经尝试了很多关于如何做的“想法”?而且我有非常大的“脏”代码……每次运行它都会崩溃。
public class MyService extends Service {
public BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
public BluetoothSocket socket;
public String readMessage;
public int BTC_STATE;
ExecutorService es;
public void onCreate() {
super.onCreate();
es = Executors.newFixedThreadPool(2);
}
}
public void onDestroy() {
super.onDestroy();
}
// ЗАПУСК СЕРВИСА
public int onStartCommand(Intent intent, int flags, int startId) {
int time = intent.getIntExtra(DashboardActivity.PARAM_TIME, 1);
int task = intent.getIntExtra(DashboardActivity.PARAM_TASK, 0);
String strMAC = intent.getStringExtra(DashboardActivity.PARAM_MAC);
String strMESS = intent.getStringExtra(DashboardActivity.PARAM_MESSAGE);
MyRun mr = new MyRun(startId, time, task,strMAC,strMESS);
es.execute(mr);
return super.onStartCommand(intent, flags, startId);
}
public IBinder onBind(Intent arg0) {
return null;
}
class MyRun implements Runnable {
int time;
int startId;
int task;
int target;
String strMAC;
String strMESS;
public MyRun(int startId, int time, int task,String strMAC,String strMESS) {
this.time = time;
this.startId = startId;
this.task = task;
this.target = 1;
this.strMAC = strMAC;
this.strMESS = strMESS;
}
public void run() {
Intent intent = new Intent(DashboardActivity.BROADCAST_ACTION);
//here, depending on task id i sent reqwest. But where i need to create listning method?
}
在 run() 中我有不同的任务...但是我需要在哪里为我的 BTE 套接字 InPutStream 创建列表方法?
【问题讨论】:
标签: java android sockets bluetooth