在不打开应用程序的情况下执行一段代码

时间:2019-07-10 07:08:47

标签: android background-process

我有一个问题,即尽管用户未打开应用程序,如何让其在后台主动运行。

例如,尽管应用程序未打开或未激活,我仍希望接收通知或运行一段代码。

2 个答案:

答案 0 :(得分:0)

要在关闭,打开或后台运行应用程序时处理通知,可以创建扩展服务

  

com.google.firebase.messaging.FirebaseMessagingService

public class YourMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(final RemoteMessage remoteMessage) {

      // Handle your notification here ...
      // Parse the notification, create your app channel,
      // set the activity to run when clicking the notification, ...

    }
}

您需要在应用的AndroidManifest.xml文件中声明您的服务:

<service android:name=".YourMessagingService ">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

您可以查看以下页面以获取更多信息: https://firebase.google.com/docs/cloud-messaging/android/receive

https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/FirebaseMessagingService

Cannot find method createNotificationChannel(NotificationChannel)

答案 1 :(得分:0)

要在后台运行任何代码,您需要创建一个服务类,当您的应用进入后台时,请使用“ startService()”方法启动该服务,但您还需要创建一个通知,告知用户该应用正在运行服务,以便系统不会终止您的服务。这是通知:

Notification.Builder builder = new Notification.Builder(this)
            .setContentTitle("Title")
            .setContentText("content");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
             builder.setChannelId(channelId)

    //Make this notification ongoing so it can’t be dismissed by the user//

            .setOngoing(true)
            .setSmallIcon(R.drawable.notification_icon);
    startForeground(id, builder.build());

并在服务类的onCreate内编写您的逻辑。希望对您有帮助

相关问题