【发布时间】:2019-09-04 20:46:10
【问题描述】:
我有一个问题,我需要从服务访问活动中的视图。我认为这样做的一个好方法是传递活动上下文,然后使用它来访问视图。然而,当我运行它时,它会抛出一个空错误,这意味着对象(视图)为空。这是代码,我想知道如何解决这个问题:
public class Purchase extends AppCompatActivity {
private TextView purchaseAmount;
private Button but;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase);
but = (Button) findViewById(R.id.makePurBut);
purchaseAmount = (TextView) findViewById(R.id.purchaseAmout);
Intent i = new Intent(Purchase.this, MyHostApduService.class);
MyHostApduService myHostApduService = new MyHostApduService(Purchase.this);
startService(i);
}
}
public class MyHostApduService extends HostApduService {
static Context context;
public MyHostApduService(Context context)
{
this.context = context;
}
public int onStartCommand(Intent intent, int flags, int startId) {
textView = (TextView)((Activity)context).findViewById(R.id.purchaseAmout);
but = (Button)((Activity)context).findViewById(R.id.makePurBut);
return flags;
}
}
【问题讨论】:
-
我很惊讶 android 甚至允许您在这样的嵌套类中创建服务 - 您能够在清单中声明它吗?
标签: android android-activity android-service android-context