0

アプリが現在画面上で開いていないときに、メイン アクティビティからブロードキャスト レシーバーに文字列を渡すときに問題が発生しています。

MainActivity クラスが作成されると、インテント フィルターはブロードキャスト レシーバーを介して正しい情報を返しますが、ユーザーが電話のホーム画面に移動するとすぐに、レシーバーがオフスクリーンでトリガーされると、ブロードキャスト レシーバーはトーストに対して「null」を返し始めます。

1.新しい意図

Intent home_page = new Intent(newIntent.this,MainActivity.class);

 ownAddress  = ""+customInput.getText().toString();
  home_page.putExtra("session_number", ""+ownAddress);

startActivity(home_page);


2. MainActivity.java:

public class MainActivity extends DroidGap {
SmsReceiver mAppReceiver = new SmsReceiver();

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

    Bundle bundle = getIntent().getExtras();
    final String ownAddress  = bundle.getString("session_number");

    registerReceiver(mAppReceiver, new IntentFilter("SmsReceiver"));
     Intent intent = new Intent("SmsReceiver");
      intent.putExtra("passAddress", ownAddress);
    sendBroadcast(intent);

 }

}


3.SmsReceiver.java :

public class SmsReceiver extends BroadcastReceiver {

 public void onReceive(Context context, Intent intent) {

    Toast showme = Toast.makeText(context,"Number: "+intent.getExtras().get("passAddress"),Toast.LENGTH_LONG);
    showme.show();

 }

}

アプリがバックグラウンドでのみ実行されている間、または MainActivity クラスがいつ作成されたかに関係なく、ブロードキャストレシーバーに文字列を渡す方法はありますか?

4

1 に答える 1

0

ここで間違っているかもしれませんが、論理的には、「レシーバーがオフスクリーンでトリガーされたときに、ブロードキャストレシーバーがトーストに対して「null」を返し始める」理由は、ユーザーがに行くときに onReceive コンストラクターに渡すコンテキストが破棄されるためですホーム画面。

文字列を渡すための 1 つの解決策は、渡したい文字列値を格納するために使用される MainActivity に public static 文字列変数を作成することだと思います。あとは、BroadcastReceiver でこの文字列に静的にアクセスするだけです。

于 2012-08-06T23:32:36.867 に答える