Android AsyncTask并发送BroadCast

时间:2015-01-04 16:34:40

标签: android android-asynctask android-broadcast

我想使用AsyncTask连续发送BroadCast,并且我发现了以下问题:

1)应用程序第二次旋转我的应用程序时崩溃。

2)我认为该程序没有发送我的BroadCast,我使用BroadCasts Monitor APP检查并且不在那里:

这是我的代码。

public class MainActivity extends Activity implements OnClickListener  {

private Button sosButton, cancelButton;
private  messageInABottle Sting;

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

    sosButton = (Button) findViewById(R.id.sosButton);
    sosButton.setOnClickListener(this); 
    cancelButton = (Button) findViewById(R.id.cancelButton);
    cancelButton.setOnClickListener(this); 

    // a little more code
}
@Override
public void onClick(View v) {

    switch (v.getId()) {
    case R.id.cancelButton:
        if(!Sting.isCancelled())
            Sting.cancel(true);
    break;
    case R.id.sosButton:
         Sting = (messageInABottle) new messageInABottle().execute("") ;
    break;}}

private class messageInABottle extends AsyncTask<String, Void, String>  {

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

        String mourseMessage = "...---...";
        final String KEY_INTENT_SOS = "I_SEND_A_SOS_TO_THE_WORLD"; 



        Intent intent = new Intent(KEY_INTENT_SOS);
        intent.putExtra("SOS", mourseMessage);


        while (true)
        {
            sendBroadcast(intent);
            if (isCancelled()) 
                break;
        }

        return null;

    }

    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(),
                "Stop SOS..",
                Toast.LENGTH_SHORT).show(); 
    }

    @Override
    protected void onPreExecute() {
        Toast.makeText(getApplicationContext(),
                "Sendin SOS..",
                Toast.LENGTH_SHORT).show();

    }

    @Override
    protected void onCancelled(){
        Toast.makeText(getApplicationContext(), "Cancel SOS..." ,Toast.LENGTH_SHORT).show();
    }
}}



@Override
public void onStop() {
    super.onStop();
    if(!Sting.isCancelled())
        Sting.cancel(true);
}

@Override
public void onDestroy() {
    super.onDestroy();
    if(!Sting.isCancelled())
        Sting.cancel(true);
}

2 个答案:

答案 0 :(得分:0)

对于第1部分:你可以在发生崩溃时发布一个logcat,没有它就很难知道app崩溃的原因吗?

第2部分:我尝试使用您的代码,我可以在已注册的广播接收器中看到onReceive()。 (我只是在onReceive()中放置了一些Log.i语句。

您可以查看以下内容: 1.您的BroadcastReceiver是否已注册?在XML或JAVA代码中? 2.您是否应用了正确的意图过滤器?在此特定代码段中,我使用了以下intent过滤器:

<receiver android:name="MyBroadcastReceiver"> 
            <intent-filter>
                <action android:name="I_SEND_A_SOS_TO_THE_WORLD" />                   
            </intent-filter>                
</receiver>

MainActivity.java

@Override
    public void onClick(View v) {

        Log.e("onClick", "onClick");
        switch(v.getId()){
        case R.id.startAsyncTask:
            //need to start the Asynctask here
            mAsyncTask = (MyAsyncTask)new MyAsyncTask().execute("");
            //mAsyncTask.execute("");
        }

    }

    private class MyAsyncTask extends AsyncTask<String, Void, String>  {

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            Log.e("doInBackground*****************************", "MyAsyncTask");
            String message = "This string will be the message";
            final String KEY_INTENT_SOS = "I_SEND_A_SOS_TO_THE_WORLD";
            Intent intent = new Intent(KEY_INTENT_SOS);
            intent.putExtra("SOS", message);

            sendBroadcast(intent);
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            Log.e("onPostExecute", "MyAsyncTask");
        }

        @Override
        protected void onPreExecute() {
            Log.e("onPreExecute--", "MyAsyncTask");
        }

        @Override
        protected void onCancelled(){
            Log.e("onCancelled", "MyAsyncTask");
        }

    }

我删除了while循环进行测试。

MyBroadcastReceiver.java

public class MyBroadcastReceiver  extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() == "I_SEND_A_SOS_TO_THE_WORLD"){
            Log.e("MyBroadcastReceiver" , "onReceive ============================");
        }

    }

}

答案 1 :(得分:0)

创建一个广播接收器:

private BroadcastReceiver reportBookReceiver =  new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
             // Here is your work when received the broadcast : 
            Log.i(TAG, "onReceive: BroadcastReceived");

            String  extra = intent.getStringExtra(REPORTBOOK_BROADCAST);
            if(extra!=null){
                Log.i(TAG, "onReceive: BroadcastReceived extra = " +extra);

                String download = intent.getStringExtra("downloadComplete");

                if (download!=null){
                    String fileName = null ;
                    String filePath = null ;

                    fileName = intent.getStringExtra("fileName");
                    filePath = intent.getStringExtra("filePath") ;

                    dismissPublicProgress(mContext);
                    Toast.makeText(context, "File Download Completed", Toast.LENGTH_SHORT).show();
                    new AlertDialog.Builder(mContext).setTitle(fileName).setMessage(filePath+" FilePath").create().show();

                }
            }
        }
    };

在 OnResume 中注册:

 @Override
    protected void onResume() {
        super.onResume();
       LocalBroadcastManager.getInstance(mContext).registerReceiver(reportBookReceiver, new IntentFilter(REPORTBOOK_BROADCAST));
  
    }

注销:

 @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(reportBookReceiver);

    }

现在发送广播:

@SuppressLint("StaticFieldLeak")
    public static class DownloadFileInBackGround extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... strings) {

                // ========== doInBackground work =============// 
                
                
                // Then send The BroadCast, You Can send also from OnPostExecute : 

                try {
                    Intent intent = new Intent(REPORTBOOK_BROADCAST);
                    intent.putExtra(REPORTBOOK_BROADCAST, REPORTBOOK_BROADCAST);
                    intent.putExtra("fileName", savedFileName );
                    intent.putExtra("filePath", savedFilePath.toString());
                    intent.putExtra("downloadComplete", "downloadComplete");
                    LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "5. downloadAyahInBackGround: sendBroadCastException : "+e.getMessage());
                }


            } catch (MalformedURLException malformedUrl) {
                malformedUrl.printStackTrace();
            } catch (FileNotFoundException FileNotFound) {
                FileNotFound.printStackTrace();
            } catch (ProtocolException protocolException) {
                protocolException.printStackTrace();
            } catch (IOException iOException) {
                iOException.printStackTrace();
            } finally {
                if (f != null) {
                    try {
                        f.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return null;
        }
    }

这样,就不用在 Manifest.xml 里工作了,上面的东西也可以写在 MainActivity 里面。快乐编码。