我想从第一个 Activity 开始,我想关闭第一个 Activity 。我试过了,但接收器不工作。我的应用程序中有不同的接收者,所以我希望这个 Intent 只从 FirstReceiver 接收。我该怎么做?
public class First extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Intent close = new Intent(getApplicationContext(), Close.class);
startActivity(close);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
class FirstReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Log.e("FirstReceiver","FirstReceiver");
First.this.finish();
}
}
}
这是第二堂课。
public class Close extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_close);
Intent myIntent = new Intent();
sendBroadcast(myIntent);
Log.e("onCreate","onCreate");
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.close, menu);
return true;
}
}
最佳答案
这可能对你有帮助...
public class First extends Activity {
public static final String ACTION_CLOSE = "yourPackageName.ACTION_CLOSE";
private FirstReceiver firstReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
IntentFilter filter = new IntentFilter(ACTION_CLOSE);
firstReceiver = new FirstReceiver();
registerReceiver(firstReceiver, filter);
Intent close = new Intent(getApplicationContext(), Close.class);
startActivity(close);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(firstReceiver);
}
class FirstReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("FirstReceiver", "FirstReceiver");
if (intent.getAction().equals(ACTION_CLOSE)) {
First.this.finish();
}
}
}
}
public class Close extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_close);
Intent myIntent = new Intent(First.ACTION_CLOSE);
sendBroadcast(myIntent);
Log.e("onCreate", "onCreate");
finish();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.close, menu);
return true;
}
}
关于android - 通过 Intent 关闭另一个 Activity 的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19860053/