简体   繁体   English

如何创建自定义通知 (Android)

[英]How to create a custom notification (Android)

I'm making an inventory app in Android Studio and I need some help with a custom notification function.我正在 Android Studio 中制作库存应用程序,我需要一些有关自定义通知 function 的帮助。

I want to create a notification system that outputs a notification when the user has no items in their inventory.我想创建一个通知系统,当用户的库存中没有物品时输出通知。 I have coded a basic function for notifications, but I can't seem to figure out how to output the notification when all items in the inventory have been destroyed.我已经编写了一个基本的 function 用于通知,但我似乎无法弄清楚当库存中的所有物品都被销毁时如何 output 通知。

I'm not sure if I should be calling my notification method in the DisplayInventory class or my database class.我不确定是否应该在 DisplayInventory class 或我的数据库 class 中调用通知方法。

Any help is much appreciated!任何帮助深表感谢!

This is the code for my DisplayInventory screen.这是我的 DisplayInventory 屏幕的代码。 This runs most of the functionality这运行了大部分功能

public class DisplayInventory extends AppCompatActivity {

    // Setting up all my objects from the display inventory layout, Database Helper and Adapter
    RecyclerView mRecyclerView;
    Button mAdd_button;
    MyDBHelper myDatabase;
    UserPermission notification;
    ArrayList<String> itemId;
    ArrayList<String> itemName;
    ArrayList<String> itemOwner;
    ArrayList<String> numItem;
    InventoryAdapter inventoryAdapter;
    TextView mLonelyInventory;

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

        //Instantiating necessary objects from the layout for functionality
        mRecyclerView = findViewById(R.id.recyclerView);
        mLonelyInventory = findViewById(R.id.LonelyInventory);
        mAdd_button = findViewById(R.id.add_button);

        //On Click listener that will take users from the display inventory screen to add new item screen
        mAdd_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(DisplayInventory.this, AddItem.class);
                startActivity(intent);
            }
        });

        //Instantiating ArrayLists that will be used to hold information from the DB
        myDatabase = new MyDBHelper(DisplayInventory.this);
        itemId = new ArrayList<>();
        itemName = new ArrayList<>();
        itemOwner = new ArrayList<>();
        numItem = new ArrayList<>();

        InsertDataToArray();

        inventoryAdapter = new InventoryAdapter(DisplayInventory.this, this, itemId, itemName, itemOwner, numItem);
        mRecyclerView.setAdapter(inventoryAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(DisplayInventory.this));

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1) {
            recreate();
        }
    }

    //This function uses cursors to help move data into the arrays we set up
    //setVisibility() lets me show some text when the inventory is empty
    void InsertDataToArray() {
        Cursor cursor = myDatabase.readAllData();
        if(cursor.getCount() == 0) {
            mLonelyInventory.setVisibility(View.VISIBLE);
        }
        else {
            while (cursor.moveToNext()) {
                itemId.add(cursor.getString(0));
                itemName.add(cursor.getString(1));
                itemOwner.add(cursor.getString(2));
                numItem.add(cursor.getString(3));
            }
            mLonelyInventory.setVisibility(View.GONE);
        }
    }

This is the code for my database这是我的数据库的代码

public class MyDBHelper extends SQLiteOpenHelper {

    // Setting up all variables that make up the columns in the database.
    private Context context;
    private static final String DATABASE_NAME = "InventoryList.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "my_list";
    private static final String COLUMN_ID = "_id";
    private static final String COLUMN_TITLE = "item_name";
    private static final String COLUMN_OWNER = "item_owner";
    private static final String COLUMN_NUM = "item_num";


    MyDBHelper(@Nullable Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    //Initializing the Database
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String query =
                "CREATE TABLE " + TABLE_NAME +
                        " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        COLUMN_TITLE + " TEXT, " +
                        COLUMN_OWNER + " TEXT, " +
                        COLUMN_NUM + " INTEGER);";
        sqLiteDatabase.execSQL(query);



    }

    @Override
    //This will make sure to erase the table if one already exists.
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(sqLiteDatabase);

    }

    //This method is adding functionality to add the item name, owner and number of items.
    void addItem(String itemName, String itemOwner, int numItem) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();

        cv.put(COLUMN_TITLE, itemName);
        cv.put(COLUMN_OWNER, itemOwner);
        cv.put(COLUMN_NUM, numItem);
        long result = db.insert(TABLE_NAME, null, cv);

        if (result == -1) {
            Toast.makeText(context, "Failed", Toast.LENGTH_SHORT).show();
        }
        else {
            Toast.makeText(context, "Item Added to Inventory!", Toast.LENGTH_SHORT).show();  //PENDING: May not need this toast message. AFTER MAIN SCREEN RETURN FUNCTION ADDED
        }
    }

    //This method sets up the functionality to search the entire database and read the data.
    Cursor readAllData() {
        String query = "SELECT * FROM " + TABLE_NAME;
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = null;

        if (db != null) {
           cursor = db.rawQuery(query, null);
        }
        return cursor;
    }

    //This method allows the user to update the item's data. Values that will be updated are item name, owner and number of items.
    void updateData(String row_id, String item_name, String item_owner, String item_num) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(COLUMN_TITLE, item_name);
        cv.put(COLUMN_OWNER, item_owner);
        cv.put(COLUMN_NUM, item_num);
        long result = db.update(TABLE_NAME, cv, "_id=?", new String[]{row_id});

//        if (result == -1) {
//            Toast.makeText(context, "Well, that didn't work", Toast.LENGTH_SHORT).show(); //PENDING: May not need this toast message.
//        }
//        else {
//            Toast.makeText(context, "The Update was a Success!", Toast.LENGTH_SHORT).show();  //PENDING: May not need this toast message.
//        }
    }

    void deleteItem(String row_id) {
        SQLiteDatabase db = this.getWritableDatabase();
        long result = db.delete(TABLE_NAME, "_id=?", new String[]{row_id});

//        if (result == -1) {
//            Toast.makeText(context, "Data Could Not Be Deleted! It's Still Here!", Toast.LENGTH_SHORT).show();  //PENDING: May not need this toast message.
//        }
//        else {
//            Toast.makeText(context, "The Data is No More!", Toast.LENGTH_SHORT).show();   //PENDING: May not need this toast message.
//        }
    }

    void destroyInventory() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_NAME);
    }

}

This is the code where I have tried to set up notifications这是我尝试设置通知的代码

public class UserPermission extends AppCompatActivity {

    Button mUserPermission;
    private int notificationId = 1;
    MyDBHelper myDatabase;

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

        mUserPermission = findViewById(R.id.userPermission);

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("My Channel ID", "My Channel ID", NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }


    }

    public void userPermission(View view) {
        givePermission();
    }


    public void inventoryNotification() {
        // NEW CODE ADDED HERE
        String NotificationMessage = "No inventory Items!";
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(UserPermission.this, "My Channel ID")
                .setSmallIcon(R.drawable.notifications)
                .setContentTitle("Inventory Notification")
                .setContentText(NotificationMessage)
                .setAutoCancel(true);
        //.setPriority(NotificationCompat.PRIORITY_DEFAULT);

        NotificationManagerCompat managerCompat = NotificationManagerCompat.from(UserPermission.this);
        managerCompat.notify(1,mBuilder.build());
    }

Found a solution to this problem after asking the question.提出问题后找到了解决此问题的方法。

Instead of creating a separate class that holds the notification functionality, I instead Implemented the notification functionality in the DisplayInventory class.我没有创建一个单独的 class 来保存通知功能,而是在 DisplayInventory class 中实现了通知功能。

I first created a channel in onCreate()我首先在 onCreate() 中创建了一个频道

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("My Channel ID", "My Channel ID", NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }

I then placed the code for the notification in the InsertDataToArray() method and checked if the database was empty.然后我将通知代码放在 InsertDataToArray() 方法中,并检查数据库是否为空。 If so, the notification displays.如果是这样,将显示通知。

void InsertDataToArray() {
        Cursor cursor = myDatabase.readAllData();
        if(cursor.getCount() == 0) {
            mLonelyInventory.setVisibility(View.VISIBLE);

            //ADDING NEW CODE HERE
            String NotificationMessage = "No items in Inventory!";
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(DisplayInventory.this, "My Channel ID")
                    .setSmallIcon(R.drawable.notifications)
                    .setContentTitle("Inventory Notification")
                    .setContentText(NotificationMessage)
                    .setAutoCancel(true);

            NotificationManagerCompat managerCompat = NotificationManagerCompat.from(DisplayInventory.this);
            managerCompat.notify(1,mBuilder.build());
            //NEW CODE ENDS HERE
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM