Android四大元件—BroadcastReceiver
阿新 • • 發佈:2019-02-14
自定義一個廣播接收器用來接收到廣播後執行強制下線的動作package com.example.administrator.broadcastreceiveractivity; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends BaseActivity { private NetWorkReceiver broadcastReceiver; private EditText userName; private EditText password; private Button loginButton; private Button messageButton; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); //監聽網路狀態變化的監聽 broadcastReceiver = new NetWorkReceiver(); IntentFilter intentFilter = new IntentFilter(); //加入廣播需要監聽的行為 intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); //對廣播進行註冊 registerReceiver(broadcastReceiver, intentFilter); //初始化介面控制元件 userName = (EditText) findViewById(R.id.usernameEdit); password = (EditText) findViewById(R.id.userpsdEdit); loginButton = (Button) findViewById(R.id.login); messageButton = (Button) findViewById(R.id.message); loginButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(userName.getText().toString().equals("111") && password.getText().toString().equals("111")) { Intent intent = new Intent(MainActivity.this, ContentActivity.class); startActivity(intent); } else { Toast.makeText(MainActivity.this, "點選獲取資訊按鈕獲取賬號密碼", Toast.LENGTH_SHORT).show(); } } }); messageButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(); intent.setAction("com.example.administrator.broadcastreceiveractivity.common"); sendBroadcast(intent); } }); } protected void onDestroy() { super.onDestroy(); //對廣播解除註冊 unregisterReceiver(broadcastReceiver); } }