问题
Hi Android programmers,
This question is previously asked. But there is no answer. So i need solution for that. Actually i am trying to display alert box of Mainactivity.java
calling from test.java
(Non-activity).
Thats working fine if their is no UI coding. if that code is dependent with UI means its throw errors.
Activity class :
public class Mainactivity extends Activity
{
public void message()
{
Log.i("Success : Call from non-UI & non activity class");//Upto this line working if i called message() function from other non-activity class
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
//Code
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("FMS Status Message :- ");
builder.setMessage(msg)
.setPositiveButton("OK",dialogClickListener).show();
}
}
Non-Activity class :
public class test extends BroadcastReceiver
{
Mainactvity in = new Mainactvity();
@Override
public void onReceive(Context context, Intent intent)
{
in.message();
}
}
If it is resolved then my main objective of my project will be completed. Please any one of you help me.
Thanks in advance.
回答1:
First of All, Bad Programming Practice for Android,
Mainactvity in = new Mainactvity();
You can not make a Constructor of Activity class.
And second, You are trying to display UI elements in Dialog which has not reference of Activity, in BroadcastReceiver
. Use Context of Activity (If it concern with UI) or Application for displaying Dialog in BroadcastReceiver.
回答2:
Create a Constructor
, where you can get Activity. Like this -
Activity activity;
public test (Activity activity){
this.activity = activity;
}
Now, use this activity
as argument -
AlertDialog.Builder adb=new AlertDialog.Builder(activity);
Because dialog can't be shown using just a context
. You need to provide an Activity
for that.
I answered one here
来源:https://stackoverflow.com/questions/14869284/android-to-show-alert-dialog-from-non-ui-or-non-activity-class