我正在尝试从前台服务启动我的应用程序,但它有时仅会发生,我不知道为什么。我创建了一个服务,该服务在我的应用程序关闭时保持运行。如果活动完成了该操作,则它将不会从服务中再次打开。这是该服务:
public class MQTTService extends Service {
private PowerManager.WakeLock wakeLock;
public void MQTTService() {
clientPhone = new MqttAndroidClient(this, serverUri, clientId);
clientPhone.setCallback(new MqttCallback() {
public void connectComplete(boolean b, String s) {
}
@Override
public void connectionLost(Throwable throwable) {
}
@Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Mqtt", mqttMessage.toString());
Log.e("message ", String.valueOf(mqttMessage));
Toast.makeText(MQTTService.this, "Crash Occurred", Toast.LENGTH_SHORT).show();
Intent dialogIntent = new Intent(MQTTService.this, alert.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "carcrashdetection:PARTIAL_WAKE_LOCK_TAG");
createNotificationChannel(this);
Notification notification = new NotificationCompat.Builder(this, "NOTIFICATION_CHANNEL").setSmallIcon
(R.drawable.add_car).setContentTitle("Title")
.setContentText("Content").build();
startForeground(1001, notification);
registerReceiver();
new Thread(new Runnable() {
@Override
public void run() {
MQTTService.this.MQTTService();
}
}).start();
}
@Override
public void onDestroy() {
super.onDestroy();
if (wakeLock.isHeld()) {
wakeLock.release();
}
}
public void createNotificationChannel(MQTTService mqttService) {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Channel name";
String description = "Description";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("NOTIFICATION_CHANNEL", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getApplicationContext().getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
我从日志中看到我仍在接收消息(收到的消息是启动活动的原因),但似乎并非每次都启动该活动。这是它启动的活动。
在主要活动中,我就是on create上的
Intent i = new Intent(MainActivity.this, MQTTService.class);
ContextCompat.startForegroundService(MainActivity.this, i);
ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.FOREGROUND_SERVICE},1);
我已经来了一段时间,似乎无法弄清楚。另外,主要活动不是我要启动的活动。我的目标是每当发送消息时都能够启动活动。我最好使用求职服务吗?
Ps。我摆脱了服务中的大多数mqtt方法,因为我认为不需要它们来解决此问题。让我知道是否要添加它们。