Нажатие на уведомление из приложения без значков не вызывает приложение - PullRequest
0 голосов
/ 04 ноября 2019

Я работаю над одним из встроенных приложений, которое мне нужно для заката, если я скрываю значок приложения через код, то приложение не вызывается, когда я нажимаю на уведомление о системном трее, чтобы запустить его.

Я попытался смоделировать это в примере приложения, и оно там даже не работает. Есть ли какие-либо ограничения в Google для приложений без значка запуска для того, чтобы не вызываться из уведомлений?

Мой код класса Applicaiton:

class MainApplication : Application() {


override fun onCreate() {
    super.onCreate()
    hideAppIcon()
    showNotification()

}

private fun hideAppIcon() {
    val p = packageManager
    val componentName = ComponentName(
        this,
        com.icon.notification.rel.MainActivity::class.java
    ) // activity which is first time open in manifiest file which is declare as <category android:name="android.intent.category.LAUNCHER" />
    p.setComponentEnabledSetting(
        componentName,
        PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
        PackageManager.DONT_KILL_APP
    )
}

private fun showNotification(){

    // 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) {
        val name = getString(R.string.channel_name)
        val descriptionText = getString(R.string.channel_description)
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel("local_notification", name, importance).apply {
            description = descriptionText
        }
        // Register the channel with the system
        val notificationManager: NotificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)



        // Create an explicit intent for an Activity in your app
        val intent = Intent(this, MainActivity::class.java).apply {
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
        }
        val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)

        val builder = NotificationCompat.Builder(this, "local_notification")
            .setSmallIcon(android.R.drawable.ic_dialog_email)//@android:drawable/ic_dialog_email
            .setContentTitle("My notification")
            .setContentText("Hello World!")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            // Set the intent that will fire when the user taps the notification
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)


        with(NotificationManagerCompat.from(this)) {
            // notificationId is a unique int for each notification that you must define
            notify(1000000001, builder.build())
        }
    }
}

}

Код моей деятельности:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    fab.setOnClickListener { view ->
        this.finish()
    }
}

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.menu_main, menu)
    return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    return when (item.itemId) {
        R.id.action_settings -> true
        else -> super.onOptionsItemSelected(item)
    }
}

}

Мой манифест:

<?xml version="1.0" encoding="utf-8"?>

<application
    android:name=".MainApplication"
    android:allowBackup="true"
    android:theme="@style/AppTheme">
    <activity

        android:name=".MainActivity"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Ответы [ 2 ]

0 голосов
/ 13 ноября 2019

Только что нашел причину и хотел поделиться со всеми.

Чтобы полностью скрыть значок приложения, я отключил активность средства запуска, при этом фильтр намерений для этого также отключается, так как весь компонентотключается. Поскольку намерение, которое было запущено во время нажатия на уведомление, приводит вас к действию средства запуска, основанного только на фильтре намерений, намерение выбрасывается, но действие средства запуска отключается, как и его фильтр намерений, в результате чего намерение ничего не делает.

Надеюсь, это поможет всем, кто склонен полностью скрывать значок приложения.

0 голосов
/ 04 ноября 2019
private NotificationManager alarmNotificationManager;
private void showNotification(Context context, String msg) {
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, SplashActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        int notifyID = 1;
        String CHANNEL_ID = "my_channel_01";// The id of the channel.
        CharSequence name = "Football90 Reminder";// The user-visible name of the channel.
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
        // Create a notification and set the notification channel.
        Notification notification = new Notification.Builder(context)
                .setContentTitle("Football90")
                .setContentText(msg)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setChannelId(CHANNEL_ID)
                .setContentIntent(contentIntent)
                .build();
        NotificationManager mNotificationManager =
                (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mNotificationManager.createNotificationChannel(mChannel);
        }
        // Issue the notification.
        mNotificationManager.notify(notifyID , notification);
    }else {
        alarmNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        //Create notification
        NotificationCompat.Builder alamNotificationBuilder = new NotificationCompat.Builder(
                context).setContentTitle("Football90").setSmallIcon(R.mipmap.ic_launcher)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg).setAutoCancel(true);
        alamNotificationBuilder.setContentIntent(contentIntent);

        //notiy notification manager about new notification
        alarmNotificationManager.notify(1, alamNotificationBuilder.build());

    }
}

Попробуйте этот метод, чтобы показать уведомление.

...