Уведомление системы BroadcastReceiver - PullRequest
0 голосов
/ 03 мая 2020

Мне нужно выполнить и выполнить код через 2 часа после запуска приложения. Это соединение с сервером.

Это соединение работает нормально, потому что сервер получает пакет, а приложение также получает ответ сервера.

У меня проблема в том, что после ответа сервера мне нужно показать системное уведомление, но уведомление не появляется.

 public class CheckPostsReceiver extends BroadcastReceiver {
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onReceive(Context arg0, Intent arg1) {

     MyDB db = new MyDB(arg0);
     MyNotificationTask myATaskYW = new MyNotificationTask(arg0);
     myATaskYW.execute("%$·$%::!"+db.getUltimoHash());
     notificacion(arg0);
}

class MyNotificationTask extends AsyncTask<String, Void, String> {

private static final int SERVERPORT = 10000;
/**
 * HOST
 * */
private static final String ADDRESS = "192.168.0.248";

Context context;

MyNotificationTask(Context c){
    context=c;
}

@Override
protected String doInBackground(String... values) {

    try {
        Socket socket = new Socket(ADDRESS, SERVERPORT);

        PrintStream output = new PrintStream(socket.getOutputStream());
        String request = values[0];
        output.println(request);

        InputStream stream = socket.getInputStream();
        byte[] lenBytes = new byte[16000];
        stream.read(lenBytes,0,16000);
        String received = new String(lenBytes,"UTF-8").trim();
        //cierra conexion
        socket.close();
        return received;
    }catch (UnknownHostException ex) {
        return ex.getMessage();
    } catch (IOException ex) {
        return ex.getMessage();
    }
}

@Override
protected void onPostExecute(String value){

    if (!value.isEmpty()){
        MyDB db = new MyDB(context);
        String [] data= value.split(";¬");

        if (data[0].equals("new_event")){
            if(db.getUltimoHash().equals(data[1])){

            }
        }
    }
}
}

 public void notificacion(Context context){
    // Create Notification using NotificationCompat.Builder

    Intent intent = new Intent(context, NotificationService.class);
    PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
        PendingIntent.FLAG_UPDATE_CURRENT);

NotificationCompat.Builder builder = new NotificationCompat.Builder(
        context)
        // Set Icon
        .setSmallIcon(R.drawable.icono)
        // Set Ticker Message
        .setTicker("message")
        // Set Title
        .setContentTitle("asdf")
        // Set Text
        .setContentText("message")
        // Add an Action Button below Notification
        // Set PendingIntent into Notification
        .setContentIntent(pIntent)
        // Dismiss Notification
        .setAutoCancel(true);

// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) context
        .getSystemService(Context.NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}
}

Я не знаю, что должен быть класс, который идет сюда

Intent intent = new Intent (context, NotificationService.class);

Это класс NotificationService

public class NotificationService extends Service {

public static final String CHANNEL_ID = "NotificationChanel";
Context context;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

NotificationService(Context c){
    context=c;
}

private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel serviceChannel = new NotificationChannel(
                CHANNEL_ID,
                "Foreground Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
        );

        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(serviceChannel);
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(context,"Its up", Toast.LENGTH_LONG).show();

    String input = intent.getStringExtra("inputExtra");
    createNotificationChannel();
    Intent notificationIntent = new Intent(context, CheckPostsReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context,
            0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID)
            .setContentTitle("FM UNIVERSIDAD")
            .setContentText(input)
            .setContentIntent(pendingIntent)
            .build();

    startForeground(25, notification);

    return START_NOT_STICKY;
}
}

В Манифесте я установил:

<receiver android:name=".CheckPostsReceiver"
        android:enabled="true"
        android:exported="true"></receiver>

    <receiver android:name=".NotificationService"
        android:enabled="true"
        android:exported="true"></receiver>
...