我正在研究火灾报警应用程序。基本上,我想做的是创建一个后台服务,该服务将在特定网站启动时通知用户并振动设备。该网站是由Node mcu创建的,该节点由烟雾或火焰传感器触发。我是android studio的新手,但经过一番研究,我编写了以下代码,但似乎不起作用。试图调试它,但没有人能告诉我出了什么问题吗?
这是我为该服务编写的代码-
1932 / 2576 = 0.75
“振动”和“通知”命令均在Timertask外部运行,因此我尝试在“ Timer Task”外部运行代码,但似乎不起作用。此外,该标志和“ Internet可用逻辑”是否正常工作。 预先感谢!
答案 0 :(得分:0)
更新: 调试后我做了一些更改,现在代码可以正常工作了。不知道为什么以前不是,但是现在仍然很好。谢谢!
更改后的代码为:-
public class ExampleService extends Service {
int flag2=0;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer repeatTask = new Timer();
repeatTask.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (isInternetAvailable()){
flag2 = 1;
}else{
flag2 = 0;
}
System.out.println("pingHost flag2: " + flag2 );
if (flag2 == 1) {
notif();
}
}
}, 0, 10000);
return START_STICKY; }
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return !ipAddr.equals("");
}
catch (Exception e) {
return false;
}
}
public void notif() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Fire Alarm Service")
.setContentText("Fire Detected in D building")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(5000, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
v.vibrate(5000);
}
}
}