4

放送受信機からの現在のアクティビティを閉じる必要があります。それからfinishを呼び出す方法がわかりません。おそらく、「戻る」キーのキー押下をシミュレートする方法があります。それが仕事をする限り、どんな実装でも問題ありません。

@Override
public void onReceive(Context context, Intent intent) {
// How can I finish the current activity here?
}
4

10 に答える 10

2

放送受信機で次のように書きます。 YourCurrentActivityName.this.finish();

または、this.finish();を使用してフロントアクティビティを終了できます。そのため、スタックの最後のオープンが前面に表示されます。


更新: 最初のケースのコード:

バックスタックでアクティビティを終了するためのブロードキャストレシーバーの使用:

public class ActivityFirstName extends Activity {

    private BroadcastReceiver mFinishReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // other code

        if (mFinishReceiver == null) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.example.ACTION_TERMINATE");// a string to identify your action
            mFinishReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    // How can I finish the current activity here?
                    if ("com.example.ACTION_TERMINATE".equals(intent.getAction())) {
                        ActivityFirstName.this.finish();
                    }
                }
            };
            registerReceiver(mFinishReceiver, intentFilter);
        }

        // other code

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isFinishing()) {
            if (mFinishReceiver != null) {
                unregisterReceiver(mFinishReceiver);
            }
        }
    }

}

そして、フロント/現在実行中のアクティビティ、ブロードキャストの送信者:

public class ActivitySecondName extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        // code code code

        final Button button = (Button) findViewById(R.id.button_id);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Perform action on click
                terminateBackActivities();
            }
        });
    }

    private void terminateBackActivities() {
        Intent i = new Intent("com.example.ACTION_TERMINATE"); // the two action strings MUST be same
        // i.putExtra(...); // to send extra data
        sendBroadcast(i);
    }

}
于 2013-02-04T00:04:52.737 に答える
1

BroadcastReceiver がアクティビティの内部クラスではないというコメントから、次のことを行う必要があります。別のクラスにブロードキャスト レシーバを配置するのではなく、アクティビティ内で次のように定義します。

private BroadcastReceiver mFinishReceiver = new BroadcastReceiver(){
@Override
    public void onReceive(Context context, Intent intent){
        YourActivity.this.finish();
    }
};

次に、レシーバーを onResume() に次のように登録します。

@Override
public void onResume(){
    super.onResume();
    registerReceiver(mFinishReceiver, new IntentFilter(yourIntentAction));
}

また、このレシーバーを onPause() で登録解除して、リークしないようにすることもできます。

@Override
public void onPause(){
    super.onPause();
    unregisterReceiver(mFinishReceiver);
}

次に、独自の別のクラスを持つ他のレシーバーを削除し、マニフェストでその定義を削除することもできます。上記の例では、アクティビティのクラスの内部にあるため、レシーバーはアクティビティの実行中にのみ登録されるため、いつでも問題なく finish() を呼び出すことができます。

編集: madlymad のコメントによると、メソッドを onPause() と onDestroy() ではなく onCreate() と onDestroy() に変更します。

于 2013-02-06T16:44:40.217 に答える
1

あなたは単に呼び出すことができますthis.finish();

于 2013-02-01T04:49:31.570 に答える
0

ActivityManager クラスは、現在のフォアグラウンド アクティビティを提供できます (アプリからのものでなくても)。getRunningTasksメソッドは、実行中のタスクのリストを提供します。リストの最初の要素は、最近起動されたアクティビティです。残念ながら、このメソッドは、アクティビティ自体ではなく、RecentTaskInfo 型のオブジェクトを提供するだけなので、方法はありませんそのfinish()メソッドを呼び出すには、私は信じています:/

一方、アプリから現在のアクティビティを閉じたい場合は、各アクティビティが onResume() メソッドで設定する個人クラスに静的変数を実装できます。このようにして、現在のアクティビティが何であるかを常に知ることができます。しかし、それはあなたが探しているものではないと思います。

編集: getRunningTasks は、ドキュメントにあるように、デバッグ目的のみを目的としています。

于 2013-02-04T00:15:00.937 に答える
0

使用してみてください:

Intent i = new Intent(context,intent.getClass());
于 2013-02-07T13:42:46.840 に答える
0

Android で現在のフォアグラウンド アクティビティ コンテキストを取得する方法に関する gezdy の指示に従ってください。アプリケーションのどこからでも現在のアクティビティへの参照を取得できるようにします。

そこから .finish() を呼び出して、現在のアクティビティを閉じることができます。

于 2013-02-25T17:47:49.873 に答える
0

共通の Activity クラスを作成し、この共通のクラスをすべてのアクティビティから拡張します。これにより、集中化されたコードを持つことができます。アクティビティの onStart でブロードキャスト レシーバーを登録し、onStop で登録を解除して、1 つのアクティビティのみを登録します。表示されているアクティビティは、ブロードキャスト インテントに登録されます。

サンプルコード:

public class BaseActivity extends Activity {

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerReceiver(receiver, new IntentFilter(YOUR_INTENT_FILTER)); 
    }
    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onStop()
     */
    protected void onStop(){
        unregisterReceiver(receiver);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onStart()
     */
    protected void onStart(){
        super.onStart();
        registerReceiver(receiver, new IntentFilter(YOUR_INTENT_FILTER)); 
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        /*
         * (non-Javadoc)
         * 
         * @see
         * android.content.BroadcastReceiver#onReceive(android.content.Context,
         * android.content.Intent)
         */
        @Override
        public void onReceive(Context context, Intent intent) {
            onBackPressed();//on back pressed simply calls finish()
        }
    };
} // End of BaseActivity 
// End of File
于 2013-02-08T05:59:13.873 に答える
0

他の回答で示唆されているように、ブロードキャスト レシーバー コードのアクティビティで単に finish() を呼び出すか、自分で戻るボタンを押すキー イベントをトリガーすることもできます。

this.dispatchKeyEvent(new Keyevent(ACTION_DOWN, KEYCODE_BACK)); 
于 2013-02-06T15:33:59.477 に答える
0

これがあなたに役立つかどうかはわかりませんが、一度私を助けてくれます。ここでも同じケースだと思うので、私はあなたに答えています。

ブロードキャスト レシーバーが呼び出しを受けるたびに、そのブロードキャスト メッセージをクリックすることで、任意のアクティビティに移動できます。

と同じように:

@Override
public void onReceive(Context context, Intent intent) {
    // My Notification Code
    notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    int icon = R.drawable.app_icon;
    //System.out.println("The ID Number is: "+Long.parseLong(intent.getData().getSchemeSpecificPart()) );
    contentText = intent.getStringExtra("MyMessage");
    System.out.println("The Message is: "+intent.getStringExtra("MyMessage"));
    CharSequence text = "Your tax amount due period";
    CharSequence contentTitle = "Tax Toolbox";

    long when = System.currentTimeMillis();

    intent = new Intent(context, MenuPageActivity.class); // here i am calling activity
    intent.putExtra("sixMonth", "sixMonth");
    intent.putExtra("messageSixMonth", contentText);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    notification = new Notification(icon,text,when);

    long[] vibrate = {0,100,200,300};
    notification.vibrate = vibrate;  // To vibrate the Device

    notification.ledARGB = Color.RED;
    notification.ledOffMS = 300;
    notification.ledOnMS = 300;

    notification.defaults |= Notification.DEFAULT_LIGHTS;
    //notification.flags |= Notification.FLAG_SHOW_LIGHTS;

    notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    notificationManager.notify(com.project.TaxToolbox.NotificationConstants.NOTIFICATION_ID_SIX_MONTH, notification);


}

ここで、そのアクティビティの onCreate() で、通知による呼び出しかどうかを識別する必要があります。

など:

  NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

    System.out.println("The Extra for twoMonth is:  "+getIntent().hasExtra("twoMonth"));
    System.out.println("The Extra for sixMonth is:  "+getIntent().hasExtra("sixMonth"));
    System.out.println("The Extra for EveryMonth is:  "+getIntent().hasExtra("everyMonth"));



    if(getIntent().hasExtra("sixMonth")){
        notificationManager.cancel(NotificationConstants.NOTIFICATION_ID_SIX_MONTH);
        final AlertDialog alert3 = new AlertDialog.Builder(MenuPageActivity.this).create();
        alert3.setTitle("Tax Toolbox");
        alert3.setMessage(getIntent().getExtras().getString("messageSixMonth"));
        alert3.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        alert3.setIcon(R.drawable.app_icon);
        alert3.show();

// ここで、その他の操作を実行したり、アクティビティを閉じたりできます。}

確かではありませんが、あなたに役立つかもしれません。

お役に立ちましたら、お気軽にコメントください。

于 2013-02-07T13:11:00.820 に答える
-1

以下のように、クラス finish();のすべてのタスクを完了した後に配置します。onReceive()BroadcastReceiver

 @Override
 public void onReceive(Context context, Intent intent) {
    // Do all the tasks onReceive of BroadCast Receiver
    finish(); // This finishes the current activity here....   
}
于 2013-02-08T08:55:12.793 に答える