开发者社区> 问答> 正文

我自己的Android应用导致手机崩溃

我正在尝试学习如何在Android上触发通知。该应用程序可以在虚拟设备上运行,但是当我在实际的三星Galaxy S7(Android版本:8.1.0)上尝试使用该应用程序时,每次按下通知按钮时都会显示一条消息,提示“系统用户界面已停止”,该手机会冻结手机我的手机无限期无响应,需要重启。

public class MainActivity extends AppCompatActivity {

    String CHANNEL1_ID = "Channel 1 id";
    String CHANNEL1_NAME = "Channel 1";
    String channel1_description = "Channel 1 description";
    String textTitle = "This is a title.";
    String textContent = "Some content.";
    int count = 0;

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

        Button button = (Button) findViewById(R.id.button);
        final Context context = this;

        createNotificationChannel();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL1_ID);
                builder.setSmallIcon(R.drawable.notification_image);
                builder.setContentTitle(textTitle);
                builder.setContentText(textContent);
                builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);

                NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

                // notificationId is a unique int for each notification that you must define
                notificationManager.notify(count, builder.build());

                count++;

                Log.d("TAG " + count, "onClick: ");

            }

        });

    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String name = CHANNEL1_NAME;
            String description = channel1_description;
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL1_ID, name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

}

问题来源:Stack Overflow

展开
收起
montos 2020-03-25 19:19:26 486 0
1 条回答
写回答
取消 提交回答
  • 我要做的就是将以下内容添加到模块级别的build.gradle实现“ com.android.support:support-compat:29.0.0”中,因为我的目标SDK版本为29。

    回答来源:Stack Overflow

    2020-03-25 19:19:49
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Tangram 立即下载
360手机卫士 插件化漫谈 立即下载
手机京东Crash自动分析处理系统 立即下载