Autore Topic: [API 14] Broadcast Intent non funzionante  (Letto 379 volte)

Offline Genymus

  • Nuovo arrivato
  • *
  • Post: 2
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Galaxy Note 2
  • Sistema operativo:
    Windows 7
[API 14] Broadcast Intent non funzionante
« il: 11 Luglio 2015, 23:26:45 CEST »
0
Salve a tutti, ho un problema che non riesco a risolvere:
Ho un LocalBroadcastReceiver in un IntentSerivce che avvio da un'activity.
Il problema si presenta quando provo ad inviare un broadcast dalla stessa activity che avvia il service, mentre dalle altre, la stessa procedura (con la modifica solo dell'activity da cui parte il broadcast), funziona senza problemi.

Allego le  due activity (Settings, da cui parte il Service, e Download, dove la procedura funziona correttamente) e il Service (Downloader).

Settings:
Codice (Java): [Seleziona]
package it.icgiavera.cimiterobritannico;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;

public class Settings extends Activity {
    SharedPreferences Config;
    private boolean Cursor;
    private ImageView CursorSwitch;
    private byte checkRadioByCode = 0;

    private BroadcastReceiver Messanger = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("Settings", "Received Status");
            checkServiceStatus();
        }
    };

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

        LocalBroadcastManager.getInstance(this).registerReceiver(Messanger, new IntentFilter("DownloadSettingsOut"));
        Config = getSharedPreferences("cimiterobritannico", Context.MODE_PRIVATE);

        TextView Directory = (TextView) findViewById(R.id.Settings_Directory);
        Directory.setText(Memory.Path);

        CursorSwitch = (ImageView) findViewById(R.id.Settings_CursorSwitch);
        int VideoCursor = Config.getInt("VideoCursor", -2);
        if (VideoCursor == -2) {
            Cursor = false;
            SharedPreferences.Editor editor = Config.edit();
            editor.putInt("VideoCursor", -1);
            editor.commit();
        } else {
            CursorSwitch.setImageResource(R.drawable.switch_on);
            Cursor = true;
        }

        CursorSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Cursor) {
                    CursorSwitch.setImageResource(R.drawable.switch_off);
                    Cursor = false;
                    SharedPreferences.Editor editor = Config.edit();
                    editor.putInt("VideoCursor", -1);
                    editor.commit();
                } else {
                    CursorSwitch.setImageResource(R.drawable.switch_on);
                    Cursor = true;
                    SharedPreferences.Editor editor = Config.edit();
                    editor.putInt("VideoCursor", 0);
                    editor.commit();
                }
            }
        });

        RadioGroup QualityRadios = (RadioGroup) findViewById(R.id.Settings_QualityRadios);
       
        switch (Memory.Quality) {
            case 1: QualityRadios.check(R.id.Settings_480p); break;
            case 2: QualityRadios.check(R.id.Settings_1080p); break;
        }
       
        QualityRadios.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkRadioByCode > 0) {
                    checkRadioByCode -= 1;
                } else {
                    switch (checkedId) {
                        case R.id.Settings_480p:
                            CallDownload((byte) 1);
                            break;
                        case R.id.Settings_1080p:
                            CallDownload((byte) 2);
                            break;
                    }
                }
            }
        });

        Button ShowDownload = (Button) findViewById(R.id.Settings_Download);
        checkServiceStatus();
        ShowDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent StartActivity = new Intent(Settings.this, Download.class);
                startActivity(StartActivity);
            }
        });
    }

    private void CallDownload(final byte Quality) {
        final File Resource = new File(Memory.Path);
        final AlertDialog.Builder Dialog = new AlertDialog.Builder(Settings.this);

        Dialog.setTitle(R.string.app_name);
        if (Downloader.Status) {
            Dialog.setMessage(R.string.settings_dialog_cancel);
        } else {
            String Message = getResources().getString(R.string.settings_dialog_download1);
            if (Quality == 1) {
                Message += (" 480p");
            } else {
                Message += (" 1080p");
            }

            if (Resource.exists()) {
                Message += getResources().getString(R.string.settings_dialog_download1);
            }

            Dialog.setMessage(Message);
        }
        Dialog.setPositiveButton("Si", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                if (Downloader.Status) {
                    Log.i("Setting", "Try Stop Function");
                    cancelDownload(Quality);
                } else {
                    if (!Resource.exists()) {
                        Resource.delete();
                    }
                    StartDownload(Quality);
                }
            }
        });
        Dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                RadioGroup QualityRadios = (RadioGroup) findViewById(R.id.Settings_QualityRadios);
                dialog.dismiss();
   
                if (Memory.Quality == 0) {
                    checkRadioByCode = 1;
                    QualityRadios.check(0);
                } else {
                    checkRadioByCode = 3;

                    switch (QualityRadios.getCheckedRadioButtonId()) {
                        case R.id.Settings_480p:
                            QualityRadios.check(R.id.Settings_1080p);
                            break;
                        case R.id.Settings_1080p:
                            QualityRadios.check(R.id.Settings_480p);
                            break;
                    }
                }
            }
        });

        Dialog.show();
    }

    private void cancelDownload(byte Quality) {
        if (Downloader.Status) {
            Intent stopCommand = new Intent("DownloadMsgIn");
            stopCommand.putExtra("Command", 0);
            LocalBroadcastManager.getInstance(Settings.this).sendBroadcast(stopCommand);
            Log.i("Setting", "Send Stop Command");
        }

        while (Downloader.Status) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        checkServiceStatus();
        Toast.makeText(Settings.this, "Download Annullato", Toast.LENGTH_LONG).show();

        CallDownload(Quality);
    }

    private void StartDownload(byte Quality) {
        Toast.makeText(Settings.this, "Download Avviato " + Quality, Toast.LENGTH_LONG).show();
        Memory.Quality = Quality;
        Intent StartService = new Intent(Settings.this, Downloader.class);
        startService(StartService);
    }

    private void checkServiceStatus() {
        Button DownloadButton = (Button) findViewById(R.id.Settings_Download);
        if (Downloader.Status) {
            DownloadButton.setEnabled(true);
            DownloadButton.setVisibility(View.VISIBLE);
        } else {
            DownloadButton.setEnabled(true);
            DownloadButton.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(Messanger);
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(Messanger);
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();

        LocalBroadcastManager.getInstance(this).registerReceiver(Messanger, new IntentFilter("DownloadSettingsOut"));

        checkServiceStatus();
    }

    @Override
    public void onBackPressed() {
        Toast tost = Toast.makeText(Settings.this, "ciao", Toast.LENGTH_SHORT);
        tost.show();

        finish();

        return;
    }
}

Download:
Codice (Java): [Seleziona]
package it.icgiavera.cimiterobritannico;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Download extends Activity {
    private Button downloadStop;
    private boolean Blocked = false;

    //private String getSize(int Downloaded, int Size) {       return Downloaded + "/" + Size;    }

    private BroadcastReceiver Messanger = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Integer Percent = intent.getIntExtra("Percent", -1);
            Integer Downloaded = intent.getIntExtra("Downloaded", -1);
            Integer Total = intent.getIntExtra("Total", -1);
            String Speed = intent.getStringExtra("Speed");
            Blocked = intent.getBooleanExtra("Blocked", false);
            Boolean Status = intent.getBooleanExtra("Status", false);

            ProgressBar pBar = (ProgressBar) findViewById(R.id.Download_Progressbar);
            pBar.setProgress(Percent);

            TextView tPercent = (TextView) findViewById(R.id.Download_Percent);
            tPercent.setText(Percent + " %");

            TextView tDownloaded = (TextView) findViewById(R.id.Download_Information);
            tDownloaded.setText(Functions.HumanSize(Downloaded) + "/" + Functions.HumanSize(Total) + " - " + Speed);

            if (!Status) { checkServiceStatus(); }
        }
    };

    private void checkServiceStatus() {
        TextView tStatus = (TextView) findViewById(R.id.Download_Status);
        if (Downloader.Status) {
            tStatus.setText("Download in corso...");
            downloadStop.setVisibility(View.VISIBLE);
        } else {
            if (Blocked) {
                tStatus.setText("Download bloccato");
            } else {
                tStatus.setText("Download completato");
            }
            downloadStop.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.download);

        TextView tPosition = (TextView) findViewById(R.id.Download_Position);
        tPosition.setText(Memory.Path);

        TextView tQuality = (TextView) findViewById(R.id.Download_Quality);
        if (Memory.Quality == 1) {
            tQuality.setText("480p");
        } else {
            tQuality.setText("1080p");
        }

        LocalBroadcastManager.getInstance(this).registerReceiver(Messanger, new IntentFilter("DownloadMsgOut"));

        downloadStop = (Button) findViewById(R.id.Download_StopDownload);
        checkServiceStatus();

        downloadStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("DownloadMsgIn");
                intent.putExtra("Command", 0);
                LocalBroadcastManager.getInstance(Download.this).sendBroadcast(intent);
                Log.i("Download", "Send Stop Command");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(Messanger);
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();

        LocalBroadcastManager.getInstance(this).unregisterReceiver(Messanger);
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();

        LocalBroadcastManager.getInstance(this).registerReceiver(Messanger, new IntentFilter("DownloadMsgOut"));

        checkServiceStatus();
    }
}

Downloader (Service):
Codice (Java): [Seleziona]
package it.icgiavera.cimiterobritannico;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.content.IntentFilter;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class Downloader extends IntentService {
    public static boolean Status = false;
    private static boolean ServiceStatus = false;
    private static boolean StopCommand = false;
    private static int Percent;
    private static boolean Blocked = false;
    private static int BytesDownloaded;
    private static int BytesSize;
   // private static int Quality;
    private NotificationCompat.Builder notificationBuilder;

    NotificationManager notificationManager;

    public Downloader() {
        super("Downloader");
    }

    private BroadcastReceiver Messanger = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("Service", "Stop Command Received");
            StopCommand = true;
        }
    };
///////Log.i("INFO", "FREE SPACE: " + Environment.getExternalStorageDirectory().getUsableSpace());
    @Override
    protected void onHandleIntent(Intent intent) {
        Status = true;
        ServiceStatus = true;
        Blocked = false;
        StopCommand = false;
        //Quality = Memory.Quality;
        Percent = 0;
        BytesDownloaded = 0;
        BytesSize = 1;

        Intent SettingRefresh = new Intent("DownloadSettingsOut");
        SettingRefresh.putExtra("Refresh", true);
        LocalBroadcastManager.getInstance(Downloader.this).sendBroadcast(SettingRefresh);

        LocalBroadcastManager.getInstance(this).registerReceiver(Messanger, new IntentFilter("DownloadMsgIn"));

        Intent DownloadActivity = new Intent(Downloader.this, Download.class);
        PendingIntent IntentDownload = PendingIntent.getActivity(Downloader.this, 0, DownloadActivity, 0);

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationBuilder = new NotificationCompat.Builder(Downloader.this);
        notificationBuilder.setContentTitle("Download Videoguida")
                .setContentText("Download in corso...")
                .setContentIntent(IntentDownload)
                .setAutoCancel(false)
                .setProgress(100, 0, false)
                .setSmallIcon(R.mipmap.icon);

        Thread ActionThread = new Thread() {
            @Override
            public void run() {
                Log.i("Service", "ActionThread Start");
                BytesSize = 50;

                while (BytesDownloaded < BytesSize) {
                    Log.i("Service", "Bytes: " + BytesDownloaded + " di " + BytesSize);
                    BytesDownloaded++;

                    if (StopCommand) {
                        Log.i("Service", "ActionThread Stopped by Command");
                        Blocked = true;
                        break;
                    }

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
               
                ServiceStatus = false;
                Log.i("Service", "ActionThread Stopped");
            }
        };

        Thread RefreshThread = new Thread() {
            @Override
            public void run() {
                Log.i("Service", "RefreshThread Start");
                String Speed = "n.d.";
                int downloadedBefore = 0;

                try {
                    while (ServiceStatus) {
                        Intent intent = new Intent("DownloadMsgOut");

                        Speed = (Functions.HumanSize(BytesDownloaded - downloadedBefore) + "/s");
                        downloadedBefore = BytesDownloaded;
                        int Percent = (int)((downloadedBefore * 100 / BytesSize) + 0.5);

                        notificationBuilder.setProgress(100, Percent, false);
                        notificationBuilder.setContentText(Speed);
                        notificationBuilder.setContentInfo(Percent + " %");
                        notificationManager.notify(1, notificationBuilder.build());

                        intent.putExtra("Percent", Percent);
                        intent.putExtra("Downloaded", downloadedBefore);
                        intent.putExtra("Speed", Speed);
                        intent.putExtra("Total", BytesSize);
                        intent.putExtra("Status", true);
                        intent.putExtra("Blocked", Blocked);
                        LocalBroadcastManager.getInstance(Downloader.this).sendBroadcast(intent);
                        Log.i("Service", "Percent: " + Percent);

                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (Blocked) {
                    notificationManager.cancel(1);
                } else {
                    notificationBuilder.setProgress(100, 100, false);
                    notificationBuilder.setContentText("Download Completato");
                    notificationBuilder.setContentInfo("");
                    notificationBuilder.setAutoCancel(true);
                    notificationManager.notify(1, notificationBuilder.build());
                }

                Intent intent = new Intent("DownloadMsgOut");
                intent.putExtra("Percent", 100);
                intent.putExtra("Speed", "n.d.");
                intent.putExtra("Downloaded", BytesDownloaded);
                intent.putExtra("Total", BytesSize);
                intent.putExtra("Status", false);
                intent.putExtra("Blocked", Blocked);
                LocalBroadcastManager.getInstance(Downloader.this).sendBroadcast(intent);

                intent = new Intent("DownloadSettingsOut");
                LocalBroadcastManager.getInstance(Downloader.this).sendBroadcast(intent);

                LocalBroadcastManager.getInstance(Downloader.this).unregisterReceiver(Messanger);
                Log.i("Service", "Stopped By RefreshThread");

                Status = false;

                Intent SettingRefresh = new Intent("DownloadSettingsOut");
                SettingRefresh.putExtra("Refresh", true);
                LocalBroadcastManager.getInstance(Downloader.this).sendBroadcast(SettingRefresh);

                stopSelf();
            }
        };

        ActionThread.start();
        RefreshThread.start();
    }
}

Ora, l'applicazione si dovrebbe comportare così:
1. Avvia il download da settings, se l'utente (a download iniziato) seleziona un'altra qualità, settings ferma il download
Codice (Java): [Seleziona]
...
private void cancelDownload(byte Quality) {
        if (Downloader.Status) {
            Intent stopCommand = new Intent("DownloadMsgIn");
            stopCommand.putExtra("Command", 0);
            LocalBroadcastManager.getInstance(Settings.this).sendBroadcast(stopCommand);
            Log.i("Setting", "Send Stop Command");
        }
...

2. Il service (precedentemente avviato, sta effettuando il download), riceve il messaggio da settings e ferma il download.
Codice (Java): [Seleziona]
...
private BroadcastReceiver Messanger = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
           [size=18pt][color=red][b] Log.i("Service", "Stop Command Received");[/b][/color][/size]
            StopCommand = true;
        }
    };
...

Il problema si verifica proprio quì... l'applicazione esegui il codice del settings, ma sembra che l'intent non venga mai inoltrato a downloader.
Mentre il codice (praticamente identico) su download, funziona senza problemi bloccando il download.
Codice (Java): [Seleziona]
...
downloadStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("DownloadMsgIn");
                intent.putExtra("Command", 0);
                LocalBroadcastManager.getInstance(Download.this).sendBroadcast(intent);
                Log.i("Download", "Send Stop Command");
            }
        });
...

Pensavo che fosse perchè l'intent fosse avviato dalla notificationbuilder e quindi funzionasse solo da download, ma copiando il codice su un'altra activity funziona lo stesso... perchè sembra che l'intent non voglia partire solo dall'activity che ha avviato il service?

NOTA:
Non guardate la struttura del codice, che è un test e devo ancora sistemare, il downloader non esegue il download di niente per adesso.
Perdonate le mie mancanze o errori, anzi, se trovate degli strafalcioni nel codice ed avete voglia potete darmi dei suggerimente su come correggerli.
Sono alle prime armi e si può dire che questa sia la mia prima VERA applicazione.

Grazie e cordiali saluti
Genymus

Offline Genymus

  • Nuovo arrivato
  • *
  • Post: 2
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Galaxy Note 2
  • Sistema operativo:
    Windows 7
Re:[API 14] Broadcast Intent non funzionante
« Risposta #1 il: 14 Luglio 2015, 22:40:35 CEST »
0
Nessuno sa come aiutarmi?