我创建了一个静态处理程序来更改活动中的一些UI文本和图表。在蓝牙服务中创建了一个计时器。每秒它都会检查数据库中的最后一条消息并更新时间。例如,消息来自1秒前2秒前3秒前...我存储了最后一条消息的时间,因为yyyy / mm / dd hh:mm:ss是一个java Date long值。
我的问题出现在" if(HomeActivity.mHandler!= null){"在下面的服务类中,它会出现错误"由以下原因引起:java.lang.RuntimeException:无法在未调用Looper.prepare()"的线程内创建处理程序。当我关闭并重新启动手机时会发生这种情况。 ACTION_BOOT_COMPLETED是catch并尝试运行该代码,然后抛出异常。有谁知道如何修理它?
这是我的代码:
的活动:
public class HomeActivity extends Activity {
public static Handler mHandler = new Handler() {
public void handleMessage(final Message msg) {
super.handleMessage(msg);
final Bundle bundle = msg.getData();
...
}
};
}
服务:
public class BluetoothLeService extends Service {
@Override
public void onCreate() {
// doing some other bluetooth stuffs here
...
int ONE_SECOND = 1*1000;
Timer updateTimer = new Timer();
updateTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try {
if (HomeActivity.mHandler != null) { // error
final Message msg = HomeActivity.mHandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("input", "update");
msg.setData(bundle);
HomeActivity.mHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0, ONE_SECOND);
}
广播:
public class BluetoothBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent i = new Intent(context, BluetoothLeService.class);
context.startService(i);
}
}
}
AndroidManifest:
<!-- Start the service when phone is boot. -->
<receiver android:name="com.example.BluetoothBroadcast" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
答案 0 :(得分:1)
可能应该更接近这个:
private void createHandler() {
Thread thread = new Thread() {
public void run() {
Looper.prepare();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do Work
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, 2000);
Looper.loop();
}
};
thread.start();
}