首页 > 解决方案 > 尝试在后台运行应用程序(最小化/屏幕锁定/从正在运行的应用程序中删除)

问题描述

我正在编写一个 android 应用程序,一旦检测到未接来电,它将触发 SMS。到目前为止,我能够检测到未接来电并将短信发送给来电者。

如果我运行我的应用程序,(打开 SWITCH(如智能开关)来检查正在响铃的电话并检测未接电话),然后有人来电,如果是未接电话,SMS 会正确触发。如果我最小化我的应用程序(不要锁定手机)并打开 Instagram/其他应用程序,那么短信也会发送给来电者。

但,

当我的应用程序(启用此功能的智能开关打开),但我关闭了我的应用程序,没有发送短信。当我的应用程序被最小化(屏幕锁定)时,没有消息被触发。(智能开关打开)当我的应用程序打开(屏幕锁定)时,没有消息被触发。(智能开关开启)

我是安卓新手。请帮助我,如果我的 SMART SWITCH 开启,我想保持我的应用程序运行,我的应用程序将继续监控未接来电并向来电者发送短信,无论 APP 是否在后台,屏幕是否锁定,只要我的智能开关开启。

标签: androidperformanceandroid-studiobackground

解决方案


首先你需要有关于任务的权限

<uses-permission android:name="android.permission.WAKE_LOCK" />

代码示例

 Thread(Runnable {
        // a potentially time consuming task
        val bitmap = processBitMap("image.png")
        imageView.post {
            imageView.setImageBitmap(bitmap)
        }
    }).start()

你还需要

我建议查看下一页

https://developer.android.com/guide/components/processes-and-threads

服务概览

这就是我解决它的方法。

公共类 myservices 扩展服务 { @Override public int onStartCommand(Intent intent, int flags, int startId) { Intent notificationIntent = new Intent(this, MainActivity.class); //打开MainActivity onClick PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Intent busy = new Intent(this, InterceptCall.class);
    Intent driving = new Intent(this, InterceptCall.class);
    Intent meeting = new Intent(this, InterceptCall.class);
    busy.putExtra("mode","busy");
    driving.putExtra("mode", "driving");
    meeting.putExtra("mode", "meeting");
    PendingIntent busyIntent = PendingIntent.getBroadcast(this, 1, busy, PendingIntent.FLAG_UPDATE_CURRENT); //For mini icon in notification bar
    PendingIntent drivingIntent = PendingIntent.getBroadcast(this, 2, driving, PendingIntent.FLAG_UPDATE_CURRENT); //For mini icon in notification bar
    PendingIntent meetingIntent = PendingIntent.getBroadcast(this, 3, meeting, PendingIntent.FLAG_UPDATE_CURRENT); //For mini icon in notification bar

    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Smart Mode is on ")
            .setContentText("Drag down to display modes.")
            .setContentIntent(pendingIntent)
            .setColor(Color.MAGENTA)
            .setSmallIcon(R.drawable.pingedlogo)
            .addAction(R.mipmap.ic_launcher, "Busy", busyIntent)
            .addAction(R.mipmap.ic_launcher, "Driving", drivingIntent)
            .addAction(R.mipmap.ic_launcher, "Meeting", meetingIntent)
            .build();

    startForeground(1, notification);
    return START_NOT_STICKY;
}

推荐阅读