我想在广播接收器的响应上更新UI。我必须使用一级是MainActivity,另一种是CustomReceiver。
MainActivity.java
package com.example.broadcasttest;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btn;
TextView txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn);
txt = (TextView)findViewById(R.id.txt);
txt.setText("hi.........1");
}
public void abc()
{
txt.setText("hi.........2");
}
}
这是我的CustomReceiver.java类。它接收到接收者的响应。
package com.example.broadcasttest;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class CustomReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
ActivityManager am = (ActivityManager) context
.getSystemService(Activity.ACTIVITY_SERVICE);
String packageName = am.getRunningTasks(1).get(0).topActivity
.getPackageName();
if(packageName.equals("com.example.broadcasttest"))
{
@SuppressWarnings("deprecation")
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
Log.d("activity name", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName()+" Package Name : "+componentInfo.getPackageName());
if(packageName.equals("com.example.broadcasttest") && taskInfo.get(0).topActivity.getClassName().toString().equals("com.example.broadcasttest.MainActivity"))
{
String abc = context.getClass().toString();
Toast.makeText(context, "hiiii "+abc, Toast.LENGTH_SHORT).show();
Log.e("ghorar kochu", "checking");
// Calling the method of main activity when my broadcast receiver gives me a response
MainActivity m = new MainActivity();
m.abc();
}
}
}
}
这是我的Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcasttest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/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=".Second"
android:label="@string/app_name" >
</activity>
<receiver android:name="com.example.broadcasttest.CustomReceiver">
<intent-filter >
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
</application>
</manifest>
当我运行应用程序并更改我的wifi模式时,这会给我一个NullPointer错误。
11-23 11:02:28.994: D/OpenGLRenderer(8396): Enabling debug mode 0
11-23 11:03:43.817: D/activity name(8396): CURRENT Activity ::com.example.broadcasttest.MainActivity Package Name : com.example.broadcasttest
11-23 11:03:43.824: E/ghorar kochu(8396): checking
11-23 11:03:43.866: E/hi(8396): helo
11-23 11:03:43.866: D/AndroidRuntime(8396): Shutting down VM
11-23 11:03:43.866: D/AndroidRuntime(8396): --------- beginning of crash
11-23 11:03:43.869: E/AndroidRuntime(8396): FATAL EXCEPTION: main
11-23 11:03:43.869: E/AndroidRuntime(8396): Process: com.example.broadcasttest, PID: 8396
11-23 11:03:43.869: E/AndroidRuntime(8396): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
11-23 11:03:43.869: E/AndroidRuntime(8396): at android.os.Handler.dispatchMessage(Handler.java:102)
11-23 11:03:43.869: E/AndroidRuntime(8396): at android.os.Looper.loop(Looper.java:135)
11-23 11:03:43.869: E/AndroidRuntime(8396): at android.app.ActivityThread.main(ActivityThread.java:5343)
11-23 11:03:43.869: E/AndroidRuntime(8396): at java.lang.reflect.Method.invoke(Native Method)
11-23 11:03:43.869: E/AndroidRuntime(8396): at java.lang.reflect.Method.invoke(Method.java:372)
11-23 11:03:43.869: E/AndroidRuntime(8396): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
11-23 11:03:43.869: E/AndroidRuntime(8396): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:702)
任何人都可以告诉我如何解决此错误以及我如何更新我的UI。
答案 0 :(得分:0)
感谢@MIke它解决了我的问题。我在活动所在的同一个类中使用广播。这样就不需要在Manifest.xml文件中初始化接收者名称了。
package com.example.broadcasttest;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
boolean mIsReceiverRegistered = false;
MyBroadcastReceiver mReceiver = null;
boolean isInternetPresent = false,isJsonLoad =false;
Button btn;
TextView txt;
int upFlag = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn);
txt = (TextView)findViewById(R.id.txt);
txt.setText("hi.........1");
new JsonForTest().execute();
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
upFlag =1;
}
});
}
@Override
protected void onResume() {
// Other onResume() code here
super.onResume();
if (!mIsReceiverRegistered) {
if (mReceiver == null)
mReceiver = new MyBroadcastReceiver();
registerReceiver(mReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
mIsReceiverRegistered = true;
}
}
@Override
protected void onPause() {
super.onPause();
Log.e("UNREGISTER", "UNREGISTERloG");
if (mIsReceiverRegistered) {
unregisterReceiver(mReceiver);
mReceiver = null;
mIsReceiverRegistered = false;
}
// Other onPause() code here
}
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("REGISTER", "REGISTERloG");
ConnectionDetector cd = new ConnectionDetector(getApplicationContext());
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent && upFlag ==1 && isJsonLoad) {
updateUI(intent);
}
}
}
public void updateUI(Intent intent){
Log.e("hi", "heloo");
txt.setText("hi.........2");
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
}
class JsonForTest extends AsyncTask<Void, Void, Void> {
private String msg = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
return null;
}
@Override
protected void onPostExecute(Void resultaaa) {
Log.e("hi", "helo");
isJsonLoad = true;
}
}
}
这是我的connectionDetector类。
package com.example.broadcasttest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}