需要检查广播接收器的权限;我需要在拨号时在前台显示一个应用程序,该应用程序应始终在手机上运行

如何解决需要检查广播接收器的权限;我需要在拨号时在前台显示一个应用程序,该应用程序应始终在手机上运行

我想要一个应始终在手机上运行的应用。拨*1234#,它应该出现在前台,即可见。但是当我拨打号码时,我收到消息-“连接问题或无效的 MMI 代码”。我已经从互联网上复制并编辑了代码。附有 3 段代码和 1 个清单文件。 MybroadCastReciever 用于将屏幕转至拨号号码。 InstallmentApp 和 InstallmentService 确保进程不可终止。 MainActivity 显示屏幕上显示内容。我以为我没有检查许可。所以尝试这样做。但是我应该在哪里调用 ActivityCompat.requestPermissions 以及我应该在哪里放置 onRequestPermissionsResult,它需要一个活动而不是广播接收器。我把它放在 mainActivity 中,但是只有在有权限的情况下才应该创建主活动。所以,我不认为它应该完成这项工作。我尝试放置在那里但失败了。我该怎么办?

代码

public class MainActivity extends AppCompatActivity {
    static final int REQUEST = 112;
    Context mContext = this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode,permissions,grantResults);
        switch (requestCode) {
            case REQUEST: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //do here
                    Toast.makeText(mContext,"The app was  allowed to read your store.",Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(mContext,"The app was not allowed to read your store.",Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}



public class MybroadCastReciever extends broadcastReceiver {
    @Override
    public void onReceive(Context context,Intent intent) {

        final int REQUEST = 112;
        if (Build.VERSION.SDK_INT >= 23) {
            String[] PERMISSIONS = {android.Manifest.permission.PROCESS_OUTGOING_CALLS};
            if (!hasPermissions(context,PERMISSIONS)) {
                ActivityCompat.requestPermissions((Activity) context,PERMISSIONS,REQUEST);
                //imagePath.setText("SDK>23,has no permission");
                dialer(context);

            } else {
                //do here
                //imagePath.setText("SDK>23,has no permission");
                dialer(context);

            }
        } else {
            //do here
            //imagePath.setText("SDK<23");
            dialer(context);

        }

    }

    private void dialer(Context context) {
        String ourCode = "*1234#";
        String dialednumber = getResultData();

        if (dialednumber.equals(ourCode)) {

            // My app will bring up,so cancel the dialer broadcast
            setResultData(null);

            //Intent to launch MainActivity
            Intent intent_to_mainActivity = new Intent(context,MainActivity.class);
            context.startActivity(intent_to_mainActivity);

        }
    }
    private static boolean hasPermissions(Context context,String... Permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context,permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

}
 @Override
    public void onRequestPermissionsResult(int requestCode,Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}


public class InstallmentApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        startService(new Intent(this,InstallmentService.class));
    }
}



public class InstallmentService extends Service {
    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {
        startForeground();

        return super.onStartCommand(intent,flags,startId);
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startForeground() {
        Intent notificationIntent = new Intent(this,MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,notificationIntent,0);
        notificationmanager notificationmanager = (notificationmanager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = getString(R.string.app_name);
        NotificationChannel notificationChannel = new NotificationChannel(channelId,channelId,notificationmanager.IMPORTANCE_DEFAULT);
        notificationChannel.setDescription(channelId);
        notificationChannel.setSound(null,null);

        notificationmanager.createNotificationChannel(notificationChannel);
        Notification notification = new Notification.Builder(this,channelId)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Connected through SDL")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setPriority(Notification.PRIORITY_DEFAULT)
                .build();
        startForeground(NOTIF_ID,notification);

    }
}

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myinstallments">

    <application
        android:allowBackup="true"
        android:name=".InstallmentApp"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyInstallments">
        <service android:name=".InstallmentService"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".MybroadCastReciever">
            <intent-filter>
                <action android:name="android.intent.action.NEW_OUTGOING_CALL" />
            </intent-filter>
        </receiver>
    </application>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
</manifest>

解决方法

代码:

public class MyBroadCastReciever extends BroadcastReceiver {
    @Override
    public void onReceive(Context context,Intent intent) {

        dialer(context);

    }

    private void dialer(Context context) {
        String ourCode = "*1234#";
        String dialedNumber = getResultData();

        if (dialedNumber.equals(ourCode)) {

            // My app will bring up,so cancel the dialer broadcast
            setResultData(null);

            //Intent to launch MainActivity
            Intent intent_to_mainActivity = new Intent(context,MainActivity.class);
            intent_to_mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

            context.startActivity(intent_to_mainActivity);

        }
    }
}


public class InstallmentApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        startService(new Intent(this,InstallmentService.class));
    }
}

public class InstallmentService extends Service {
    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {
        startForeground();

        return super.onStartCommand(intent,flags,startId);
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startForeground() {
        Intent notificationIntent = new Intent(this,MainActivity.class);

        PendingIntent pendingIntent = PendingIntent.getActivity(this,notificationIntent,0);
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = getString(R.string.app_name);
        NotificationChannel notificationChannel = new NotificationChannel(channelId,channelId,NotificationManager.IMPORTANCE_DEFAULT);
        notificationChannel.setDescription(channelId);
        notificationChannel.setSound(null,null);

        notificationManager.createNotificationChannel(notificationChannel);
        Notification notification = new Notification.Builder(this,channelId)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("Connected through SDL")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setPriority(Notification.PRIORITY_DEFAULT)
                .build();
        startForeground(NOTIF_ID,notification);

    }
}

public class MainActivity extends AppCompatActivity {
    static final int REQUEST = 112;
    Context mContext = this;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final int REQUEST = 112;
        if (Build.VERSION.SDK_INT >= 23) {
            String[] PERMISSIONS = {android.Manifest.permission.PROCESS_OUTGOING_CALLS};
            if (!hasPermissions(mContext,PERMISSIONS)) {
                ActivityCompat.requestPermissions((Activity) mContext,PERMISSIONS,REQUEST);
                //imagePath.setText("SDK>23,has no permission");
                //dialer(context);

            } else {
                //do here
                //imagePath.setText("SDK>23,has no permission");
                //dialer(context);

            }
        } else {
            //do here
            //imagePath.setText("SDK<23");
            //dialer(context);

        }
    }
    private static boolean hasPermissions(Context context,String... permissions) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(context,permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
    @Override
    public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode,permissions,grantResults);
        switch (requestCode) {
            case REQUEST: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //do here
                    Toast.makeText(mContext,"The app was  allowed to read your store.",Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(mContext,"The app was not allowed to read your store.",Toast.LENGTH_LONG).show();
                }
            }
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?