我的程序流程是
我的问题是5:“活动实例为空”
我的代码是
public class MainActivity extends Activity {
static MainActivity Iinstance;
private String ServiceName = myService.class.getCanonicalName();
ServiceStatus servicestatus = new ServiceStatus();
static Handler handler = new Handler();
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setSoftInputMode(
LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.textView1);
Iinstance = this;
Button B;
//there is clicklistener for B to start service.
}
class AA{
void A(String html){
tv.setText(html);
}
}
和服务代码
public class myService extends Service {
//fields
public int onStartCommand(Intent i, int flags, int startId) {
//code to start TimerTask.
}
//register the receiver.
CancelReceiver receiver = new CancelReceiver();
intentFilter = new IntentFilter();
intentFilter.addAction("MY_ACTION");
registerReceiver(receiver, intentFilter);
return START_REDELIVER_INTENT;
}
class task extends TimerTask{
@Override
public void run() {
try {//get html from webviewClient
handlers.post(new Runnable(){
@Override
public void run() {
//webView load URL.I have two doubts around this.
WebView webView = new WebView(myService.this);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new HogeWebViewClinet());
webView.addJavascriptInterface(new WebViewLogger(), "webViewLogger");
String Url = (String) map.get("URL");
webView.loadUrl(Url);
}
});
}
}
class HogeWebViewClinet extends WebViewClient {
@Override public void onPageFinished(WebView view, String url) {
//throw the html from webview to "class WebViewLogger"as "String str"by loading javascript.
view.loadUrl("javascript:window.webViewLogger.log(document.documentElement.outerHTML);");
}
}
class WebViewLogger {
public void log(String str) {
Intent broadcastIntent = new Intent();
broadcastIntent.putExtra("Status", str);
broadcastIntent.setAction("MY_ACTION");
sendBroadcast(broadcastIntent);
}
}
}
然后去广播班。
public class Receiver扩展BroadcastReceiver {
String serviceResult = null;
@Override
public void onReceive(Context arg0, Intent intent) {
AA aa = MainActivity.Iinstance.new AA(); //threw error in this line.
aa.a(intent.getStringExtra(Status);
}
就是这样。
为什么“MainActivity.Iinstance.new AA();”为空?
我的猜测为什么活动变为空
毕竟,我无法解决这个问题,但我尝试了很多解决方案。
请帮帮我。
感谢。
答案 0 :(得分:1)
您无法保留活动的静态变量,这会导致泄漏和错误!
您的活动将由Android系统重新创建和删除,具体取决于各种条件(需要内存资源,配置更改等)。
您应该使用Intent在您的Activity和您的服务之间实现通信。
如果您不想每次都创建新活动,请将活动launchMode
设置为singleTop
。然后,您需要在活动的onNewIntent(Intent)
方法中处理意图
您无法在服务中使用webView。你必须使用像HttpUrlConnection
这样的类。有关详细信息,请参阅Connect and Download Data