Android O 前台服务 - 如何处理与活动的通信,即使应用程序被从后台杀死或重新启动
创始人
2024-08-14 21:00:45
0次

在 Android O 及更高版本中,应用程序在后台运行时,前台服务需要显示一个通知,以便用户知道服务正在运行。当应用程序被杀死或重新启动时,前台服务需要能够与活动进行通信。以下是一个处理与活动通信的示例:

首先,在 AndroidManifest.xml 文件中声明前台服务:


接下来,创建一个前台服务类 MyForegroundService:

public class MyForegroundService extends Service {
    private static final String CHANNEL_ID = "ForegroundServiceChannel";
    private static final String ACTION_STOP_SERVICE = "StopService";

    private MyBroadcastReceiver receiver;

    @Override
    public void onCreate() {
        super.onCreate();
        receiver = new MyBroadcastReceiver();
        registerReceiver(receiver, new IntentFilter(ACTION_STOP_SERVICE));
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        createNotificationChannel();
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

        Intent stopIntent = new Intent(this, MyForegroundService.class);
        stopIntent.setAction(ACTION_STOP_SERVICE);
        PendingIntent stopPendingIntent = PendingIntent.getService(this, 0, stopIntent, 0);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Foreground Service")
                .setContentText("Service is running")
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(pendingIntent)
                .addAction(R.drawable.ic_stop, "Stop Service", stopPendingIntent)
                .build();

        startForeground(1, notification);

        // 在此处处理与活动的通信逻辑
        if (intent != null && intent.hasExtra("message")) {
            String message = intent.getStringExtra("message");
            sendMessageToActivity(message);
        }

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Foreground Service Channel",
                    NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
    }

    private void sendMessageToActivity(String message) {
        Intent intent = new Intent(MainActivity.ACTION_MESSAGE_RECEIVED);
        intent.putExtra("message", message);
        sendBroadcast(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_STOP_SERVICE)) {
                stopSelf();
            }
        }
    }
}

在活动 MainActivity 中,你可以接收来自前台服务的广播消息:

public class MainActivity extends AppCompatActivity {
    public static final String ACTION_MESSAGE_RECEIVED = "MessageReceived";
    private MyBroadcastReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        receiver = new MyBroadcastReceiver();
        registerReceiver(receiver, new IntentFilter(ACTION_MESSAGE_RECEIVED));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ACTION_MESSAGE_RECEIVED)) {
                String message = intent.getStringExtra("message");
                // 处理来自前台服务的消息
                Toast.makeText(MainActivity.this, "Received message: " + message, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

这样,你就可以在前台服务中使用 sendMessageToActivity() 方法发送消息,然后在 MainActivity 中接收并处理这些消息了。

相关内容

热门资讯

现有关情况通报如下透视挂!荷塘... 现有关情况通报如下透视挂!荷塘辅助透视挂,乐山游戏中心是真的有外挂,切实确实有挂1、乐山游戏中心破解...
必备辅助推荐开挂!心悦辽宁麻将... 必备辅助推荐开挂!心悦辽宁麻将辅助透视挂,微友麻将真的是有外挂,确实真的有挂1)心悦辽宁麻将辅助插件...
一分钟揭秘辅助!欢乐龙城3辅助... 一分钟揭秘辅助!欢乐龙城3辅助透视挂,同城花牌是有外挂,确实有挂神器1、欢乐龙城3辅助软件下载优化,...
揭秘真相开挂!白银岛辅助透视挂... 揭秘真相开挂!白银岛辅助透视挂,九九互娱是真的有外挂,其实有挂助手1、每一步都需要思考,不同水平的挑...
攻略讲解辅助!微乐广西麻将辅助... 攻略讲解辅助!微乐广西麻将辅助透视挂,边锋老友宁安麻将确实有外挂,一直有挂方针1、边锋老友宁安麻将辅...
2分钟细说辅助!爱玩辽宁麻将辅... 2分钟细说辅助!爱玩辽宁麻将辅助透视挂,传奇游戏休闲是真的有外挂,一贯有挂方法1、上手简单,内置详细...
终于清楚辅助!天龙座大厅辅助透... 终于清楚辅助!天龙座大厅辅助透视挂,天天游戏是有外挂,好像有挂教程1)天龙座大厅辅助插件:进一步探索...
揭秘攻略开挂!天天休闲辅助透视... 揭秘攻略开挂!天天休闲辅助透视挂,雀友会2广东潮汕麻将是有外挂,真是有挂详情1、操作简单,无需雀友会...
据文件显示辅助!纳祥游戏辅助透... 据文件显示辅助!纳祥游戏辅助透视挂,福州麻将是有外挂,好像有挂辅助1、下载好纳祥游戏透视辅助下载之后...
无独有偶辅助!哈哈乐辅助透视挂... 无独有偶辅助!哈哈乐辅助透视挂,中至余干麻将确实有外挂,都是有挂头条1、下载好中至余干麻将脚本下载之...