@blog.justoneplanet.info

日々勉強

Androidで圏外になった時に処理をする

■実装

以下の様なBroascastReceiverを用意する。

public class ConnectionReceiver extends BroadcastReceiver {
    private Observer mObserver;
    public ConnectionReceiver(Observer observer) {
        mObserver = observer;
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info == null) {
            mObserver.onDisconnect();
        }
        else {
            mObserver.onConnect();
        }
    }
    interface Observer {
        void onConnect();
        void onDisconnect();
    }
}

MainActivity

以下のようにActivityを実装する。

public class MainActivity extends ActionBarActivity implements ConnectionReceiver.Observer {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk);
        IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
        mConnectionReceiver = new ConnectionReceiver(this);
        registerReceiver(mConnectionReceiver, filter);
    }
    @Override
    protected void onDestroy() {
        unregisterReceiver(mConnectionReceiver);
        super.onDestroy();
    }
    @Override
    public void onConnect() {
        Toast.makeText(getApplicationContext(), "onConnect", Toast.LENGTH_LONG).show();
    }
    @Override
    public void onDisconnect() {
        Toast.makeText(getApplicationContext(), "onDisconnect", Toast.LENGTH_LONG).show();
    }
}

android.permission.ACCESS_NETWORK_STATEがpermissionに必要になる。

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment