N
N
Niki_1112014-07-08 16:18:11
Android
Niki_111, 2014-07-08 16:18:11

How to call the notification function not from the MainActivity class?

disclaimer:
I'm not very close to programming myself, but I'm trying to modify an open source application a little.
The goal at first glance is quite simple: to add a notification to the application under certain conditions.
Because I am a beginner, so for tests I added a button to the application, when pressed, a reaction to the desired event is simulated. And I screwed the notification call function to this button. (All improvements were made in the MainActivity class.) Everything worked as it should: when the button was pressed, the corresponding notification was called.

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_refresh:
                refreshMenuItem = item;
                // load the data from server
                new RefreshData().execute();
                return true;
            default:
                return super.onOptionsItemSelected(item);

                // my added test function
            case R.id.action_go:
                refreshMenuItem = item;
                // test alert
                testAlertNotify();
                return true;
        }
    }

public void testAlertNotify(){
        JSONParse jp = new JSONParse();
        Action action = jp.getAction();
        
        SendNotification(action.getDescription());
    }



    public void SendNotification(String  action){
        
        Context context = getApplicationContext();

        Intent notificationIntent = new Intent(context, LoginActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context,0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        NotificationManager nm = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        Resources res = context.getResources();
        Notification.Builder builder = new Notification.Builder(context);

        builder.setContentIntent(contentIntent)
                // try vibrate
                .setVibrate(new long[]{0, 200, 200, 600, 600})

                .setSmallIcon(R.drawable.run_icon)
                        // большая картинка
                .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.run_icon))
                        //.setTicker(res.getString(R.string.warning)) // текст в строке состояния
                .setTicker("Тестовое оповещение" + action)
                .setWhen(System.currentTimeMillis()) // java.lang.System.currentTimeMillis()
                .setAutoCancel(true)
                .setContentTitle("Action = " + action)
                 .setContentText("Action = " + action); // Текст уведомленимя

                // try sound
                Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                builder.setSound(uri);

        Notification n = builder.getNotification();

        nm.notify(101, n);
    }

Difficulties began when trying to call the notification function from another class with timeout porverifications. Why was the SmartCheckerTimer class created with a function from which I'm trying to trigger a notification after the test value changes. The counter works normally, but after reaching the threshold value ( GlobalVars_my ) it stops. (I checked by calling Alert in the application with the value of the test variable, a crutch method, but I don’t know any other) In general, attempts to figure it out were varied, and the classic call and inheritance of the MainActivity class followed by an attempt to call the desired function, and adding a duplicate function to the SmartCheckerTimer class to call a notification ( SendNotification1). But I feel I'm digging in the wrong direction and ran into the wall.
The last option described is to add a duplicate function (SendNotification1) to the SmartCheckerTimer class to call a notification.
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void run() {
        try {
            _detector = new ConnectionDetector(_context);
            while (true) {
                SendNotification1(action.getDescription());
                // Через 10 секунд еще раз получаем данные
                Thread.sleep(10000);
                if (_detector.isConnectingToInternet()) {
                    GlobalVars_my.countVar++;
                    if (GlobalVars_my.countVar >= 2) {
                        SendNotification1(action.getDescription());
                    }
                }
            }
        } catch (Exception exception) {
            ErrorsList.AddError(exception.toString());
        }
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Yakushev, 2014-07-10
@VYakushev

1. Create a service that will take data from the server. The service is required to work in the background.
2. Teach the activity you need to work either with a service or with an intermediate class to get the necessary data.
3. Notification is generated by the server, but with a link to the activity. Activity displays the required data when opened.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question