異なるクラスのオブジェクトにアクセスしようとすると問題が発生します。私は Android プロジェクトを使用しており、Activity を拡張する MainActivity クラスから socketconnection を実行しました。次に、BroadcastReceiver を拡張する SmsReceiver という別のクラスを作成して、自分の電話 (エミュレーター) に送信されるメッセージを取得できるようにしました。MainActivity クラスの outputstream オブジェクトを使用するには、SmsReceiver クラスが必要ですが、それに到達する方法がわかりません。MainActivity の新しいインスタンスを作成できません。
どうにかして outputstream オブジェクトを SmsReceiver クラスに送信できますか? いくつかのヒントが得られたことを願っています。事前に感謝します。
さて、私はインターフェースソリューションに行きましたが、また立ち往生しています!
ここに私のクラスがあります:
主な活動:
public class MainActivity extends Activity implements MainInterface
{
try {
out = new PrintWriter(clientSocket.getOutputStream());
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException ex) {
System.err.println("Error in creating Streams:" + ex.toString());
return;
}
public PrintWriter getOutputStream() {
return out;
}
}
メインインターフェイス:
public interface MainInterface {
public PrintWriter getOutputStream();
}
SMS受信者:
public class SmsReceiver extends BroadcastReceiver{
MainInterface mainInterface = new MainActivity(); ///// <------
PrintWriter out; //// <--------
@Override
public void onReceive(Context context, Intent intent) {
mainInterface.getOutputStream(); ////// <------------
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if(bundle != null){
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for(int i = 0; i < pdusObj.length; i++){
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
out.println("senderNum: "+ senderNum + "; message: " + message);
out.flush(); /// these two lines
}
}
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
何らかの理由で、インターフェイスを介して取得した PrintWriter はnullであり、デスクトップ上の入力ストリーム ( out.println()を実行するときにメッセージを受信する必要があるプログラム) はメッセージを取得しません。in.readLine()。インターフェイスを間違った方法でインスタンス化していますか、それとも何が起こっていますか?
logcat エラー出力は次のとおりです: 09-15 14:13:55.880: E/SmsReceiver(1361): Exception smsReceiverjava.lang.NullPointerException