我想在收到包含“运行活动”的短信时运行activityiwanttorun.classActivity
。当收到包含文本“runactivity”的短消息时,if语句在祝酒时工作。
但是它没有在activityiwanttorun.class中显示toast“youhavecalledyoursecondactivity”语句--
有人能告诉我这里出了什么事吗..我只想看到我的活动-“activityiwanttorun”在收到短信时运行。
incomingsms.java中
public class IncomingSms extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
@Override
public void onReceive(Context context, Intent 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();
if(message.contains("RunActivity")) {
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
Intent intent2 = new Intent(context,ActivityIwanttoRun.class);
context.startActivity(intent2);
toast.show();
}
}
}
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
活动iwanttorun.java
public class ActivityIwanttoRun extends Activity {
private static final String TAG = "ActivityIwanttoRun";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
updateUI();
}
private void updateUI() {
Toast.makeText(this, "You have called your second activity",Toast.LENGTH_LONG ).show();
}
}
显示
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ActivityIwanttoRun">
</activity>
<receiver android:name=".IncomingSms">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
谢谢您!
最佳答案
首先你要启动LocationActivity而不是ActivityIwanttorun
改变
Intent intent2 = new Intent(context,LocationActivity.class);
context.startActivity(intent2);
到
Intent intent2 = new Intent(context,ActivityIwanttoRun.class);
context.startActivity(intent2);
从
Activity
调用BroadcastReceiver
的正确方法是Intent intent2 = new Intent(context,ActivityIwanttoRun.class);
context.startActivity(intent2);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent2);