一、开始启程
Log的快捷方式:logd/logt等等
二、探究活动
1.使用Menu
建立menu文件夹,新建一个叫main的菜单文件:
在FirstActivity中重写onCreateOptionsMenu()和onCreateOptionsMenu()方法:
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main,menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add_item:
break;
case R.id.remove_item:
break;
default:
}
return true;
}
销毁一个活动:finish();
2、使用Intent在活动之间穿梭
启动另一个活动:
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
startActivity(intent);
隐式:
在manifest文件中sencondacitvity标签添加如下:
Intent intent = new Intent("com.lewanjiang.activitytest.ACTION_START");
startActivity(intent);
同时可添加category。:
int1.addCategory("com.lewanjiang.activitytest.MY_CATEGORY");
添加后不要忘记在manifest文件中声明category。
Intent更多用法:打开网址和拨打电话
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://bing.com"));
startActivity(intent);
Intent intent1 = new Intent(Intent.ACTION_DIAL);
intent1.setData(Uri.parse("tel:10088"));
startActivity(intent1);
响应打开网页:在manifest的activity的
向下一个活动中传递数据:
方法一:
第一个活动中:
String data = "hello bob";
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("tran",data);
startActivity(intent);
第二个活动中:
Intent intent = getIntent();
String data = intent.getStringExtra("tran");
常用写法:
第一个活动中:
SecondActivity.actionStart(FirstActivity.this,"dat1","dat2");
第二个活动中:
public static void actionStart(Context context,String data1,String data2) {
Intent int1 = new Intent(context,SecondActivity.class);
int1.putExtra("par1",data1);
int1.putExtra("par2",data2);
context.startActivity(int1);
}
返回数据给第一个活动:
第一个活动中:
Intent int1 = new Intent(FirstActivity.this,SecondActivity.class);
startActivityForResult(int1,1);
@Overrid
protected void onActivityResult(int reqCod,int resCod,Intent data){
switch (reqCod) {
case 1:
if (resCod == RESULT_OK) {
String retDat = data.getStringExtra("tran");
Log.d("FirstActivity", retDat);
}
break;
default:
}
}
第二个活动中:
Intent int1 = new Intent();
int1.putExtra("tran","Hello bob again");
setResult(RESULT_OK,int1);
响应返回键时,可将以上代码写在onBackPredded()中。
典型生命周期:onCreate、onStart(前台)、onResume(可见)、onPause、onStop、onDestroy、onRestart
if (savedInstanceState != null) {
String test = savedInstanceState.getString("extra_test");
Log.d(TAG,"[onCteate]restore extra_test:" + test);
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG,"onSaveInstanceState");
outState.putString("extra_test","haha");
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String test = savedInstanceState.getString("extra_test");
Log.d(TAG,"[onRestoreInstanceState]restore extra_test" + test);
}
内存不足Activity被杀死时与被销毁时一致
避免Activity被重新创建:设置android:configChanges属性
启动模式:standard/singleTop/singleTask/singleInstance 在manifest文件中修改:android:launchMode="singleTask"
Flags:
常用Flags:FLAG_ACTIVITY_NEW_TASK、FLAG_ACTIVITY_SINGLE_TOP、FLAG_ACTIVITY_CLEAR_TOP、FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
找到当前活动和退出所有活动:
public class BaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
Log.d("BaseActivity",getClass().getSimpleName());
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
}
public class ActivityCollector {
public static List acts = new ArrayList<>();
public static void addActivity(Activity act) {
acts.add(act);
}
public static void removeActivity(Activity act) {
acts.remove(act);
}
public static void finishAll() {
for (Activity act:acts) {
if (!act.isFinishing()) {
act.finish();
}
}
}
}
三、UI开发
基本控件与布局
android:gravity、android:textSize、android:textColor、android:textAllCaps、android:layout_gravity、android:hint、android:maxLines
textView属性:
点击;android:clickable="true"
Button:
android:textAllCaps
implement View.OnClickListener
public void onClick(View v){ switch(v.getid()){ case: ...} }
EditText:
android:hint、android:maxLines
String inpTex=editText().getText().toString();
ImageView:
android:src
imaVie.setImageResource(R.drawable.hah);
ProgressBar:
style="?android:attr/progressBarStyleHorizontal"
android:max
if(prBar.getVisibility() == View.GONE)
proBar.setVisibility(View.VISIBLE);
int prooo=proBar.getProgress();
proBar.setProgress(666);
AlertDialog:
AlertDialog.Builder dia = new AlertDialog.Builder(MainActivity.this);
dia.setTitle("TITLE");
dia.setMessage("hahahahaha");
dia.setCancelable(true);
dia.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("MainActivity","haha");
}
});
dia.setNegativeButton("Cancle", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d("MainActivity","heihei");
}
});
dia.show();
progressdialog已停用
四种基本布局:
LinearLayout
RelativeLayout(推荐使用):
android:layout_alignParentLeft/layout_alignParentRight/layout_alignParentTop/layout_alignParentBotton/layout_alignParentlayout_centerInParent/layout_above/layout_below/toLeftOf/toRightOf
FrameLayout:
android.support.percent.PercentFrameLayout:
compile 'com.android.support:percent:24.2.2
app:layout_widthPercentapp:layout_heightPercent
自定义布局:
隐藏标题栏:
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
创建自定义控件:
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.title,this);
Button titleBack = (Button) findViewById(R.id.title_back);
Button titleEdit = (Button) findViewById(R.id.title_edit);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),"haha",Toast.LENGTH_SHORT).show();
}
});
}
}
ListView简单用法:
private String[] data = {"a","b","c","d","e","f","g"};
ArrayAdapter ada = new ArrayAdapter(
MainActivity.this,android.R.layout.simple_list_item_1,data);
ListView lisVie = (ListView) findViewById(R.id.list_view);
lisVie.setAdapter(ada);
复杂用法:
public class Fruit {
private String name;
private int imageId;
public Fruit(String name,int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
public class FruitAdapter extends ArrayAdapter {
private int resourceId;
public FruitAdapter(Context context, int textViewResouceId, List objects) {
super(context,textViewResouceId,objects);
resourceId = textViewResouceId;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
Fruit fruit = getItem(position);
View view;
ViewHolder viewHolder;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
viewHolder = new ViewHolder();
viewHolder.fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
viewHolder.fruitName = (TextView) view.findViewById(R.id.fruit_name);
view.setTag(viewHolder);
} else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.fruitImage.setImageResource(fruit.getImageId());
viewHolder.fruitName.setText(fruit.getName());
return view;
}
class ViewHolder {
ImageView fruitImage;
TextView fruitName;
}
}
public class MainActivity extends AppCompatActivity {
private List fruitList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruits();
FruitAdapter adapter = new FruitAdapter(MainActivity.this,R.layout.fruit_item,fruitList);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
Fruit fruit = fruitList.get(position);
Toast.makeText(MainActivity.this,fruit.getName(),Toast.LENGTH_SHORT).show();
}
});
}
private void initFruits() {
for (int i = 0;i < 2;i++) {
Fruit apple = new Fruit("Apple",R.drawable.ic_launcher_background);
fruitList.add(apple);
Fruit banana = new Fruit("Banana",R.drawable.ic_launcher_background);
fruitList.add(banana);
}
}
}
1.概述:
RecyclerView的设计与ListView、GridView类似,也使用了Adapter,不过该Adapter并不是ListView中的Adapter,而是RecyclerView的一个静态内部类。该Adapter有一个泛型参数VH,代表的就是ViewHolder。RecyclerView还封装了一个ViewHolder类型,该类型中有一个itemView字段,代表的就是每一项数据的根视图,需要在构造函数中传递给ViewHolder对象。RecyclerView这么设计相当于将ListView的Adapter进行了再次封装,把getView函数中判断是否含有缓存的代码段封装到RecyclerView内部,使这部分逻辑对用户不可见。用户只需要告诉RecyclerView每项数据是怎么样的以及将数据绑定到每项数据上,分别对应的函数为onCreateViewHolder函数、onBindViewHolder函数,当然还需要通过getItemCount告诉RecyclerView有多少项数据,以往适用于ListView的 Adapter中的getView函数中的逻辑就不需要用户来处理了。
基本用法如下,导入listview项目中的fruit类和fruit_item.xml:
public class FruitAdapter extends RecyclerView.Adapter {
private List mFruLis;
static class ViewHolder extends RecyclerView.ViewHolder {
ImageView fruitImage;
TextView fruitName;
public ViewHolder(View vie) {
super(vie);
fruitImage = (ImageView) vie.findViewById(R.id.fruit_image);
fruitName = (TextView) vie.findViewById(R.id.fruit_name);
}
}
public FruitAdapter(List fruLis) {
mFruLis = fruLis;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup par,int vieTyp) {
View vie = LayoutInflater.from(par.getContext()).inflate(R.layout.fruit_item,par,false);
ViewHolder hol = new ViewHolder(vie);
return hol;
}
@Override
public void onBindViewHolder(ViewHolder hol,int pos) {
Fruit fru = mFruLis.get(pos);
hol.fruitImage.setImageResource(fru.getImageId());
hol.fruitName.setText(fru.getName());
}
@Override
public int getItemCount() {
return mFruLis.size();
}
}
RecyclerView recVie = (RecyclerView) findViewById(R.id.recycler_view);
LinearLayoutManager layMan = new LinearLayoutManager(this);
recVie.setLayoutManager(layMan);
FruitAdapter ada = new FruitAdapter(fruLis);
recVie.setAdapter(ada);
2.高级用法
RecyclerView的另一大特点就是将布局方式抽象为LayoutManager,默认提供了LinearLayoutManager、GridLayoutManager、StaggeredGridLayoutManager 3种布局,对应为线性布局、网格布局、交错网格布局,如果这些都无法满足你的需求,你还可以定制布局管理器实现特定的布局方式。
RecyclerView通过桥接的方式将布局职责抽离出去,使得RecyclerView变得更灵活。例如,如果用户只需要修改RecyclerView的布局方式,只需要修改LayoutManager即可,而不需要操作复杂的RecyclerView类型。而ListView、GridView正好是相反的,它们只是布局方式不一样,但却是两个类型,它们覆写了基类AbsListView的layoutChildren函数来实现不同的布局。显然,通过组合的形式要好于通过继承,因此,RecyclerView在设计上也要好于AbsListView类族。
除此之外,RecyclerView对于Item View的控制也更为精细,可以通过ItemDecotation为Item View添加装饰,也就是在Item View上进行二次加工;又可以用过ItemAnimator为Item View添加动画。
实现横向滚动:
fruit_item.xml 把布局改为垂直方向
MainActivity添加如下代码:
layMan.setOrientation(LinearLayoutManager.HORIZONTAL);
瀑布流布局:
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL);
点击事件:
修改FruitAdapter代碼如下:
static class ViewHolder extends RecyclerView.ViewHolder {
View fruitView;
ImageView fruitImage;
TextView fruitName;
public ViewHolder(View vie) {
super(vie);
fruitView = vie;
fruitImage = (ImageView) vie.findViewById(R.id.fruit_image);
fruitName = (TextView) vie.findViewById(R.id.fruit_name);
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup par,int vieTyp) {
View vie = LayoutInflater.from(par.getContext()).inflate(R.layout.fruit_item,par,false);
final ViewHolder hol = new ViewHolder(vie);
hol.fruitView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = hol.getAdapterPosition();
Fruit fru = mFruLis.get(pos);
Toast.makeText(v.getContext(),"you clicked view" + fru.getName(),Toast.LENGTH_SHORT).show();
}
});
hol.fruitImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = hol.getAdapterPosition();
Fruit fru = mFruLis.get(pos);
Toast.makeText(v.getContext(),"you clicked image" + fru.getName(),Toast.LENGTH_SHORT).show();
}
});
return hol;
}
UI最佳实践:
public class Msg {
public static final int TYPE_RECEIVED = 0;
public static final int TYPE_SEND = 1;
private String content;
private int type;
public Msg(String content,int type) {
this.content = content;
this.type = type;
}
public String getContent() {
return content;
}
public int getType() {
return type;
}
}
public class MsgAdapter extends RecyclerView.Adapter {
private List mMsgList;
static class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout leftLayout;
LinearLayout rightLayout;
TextView leftMsg;
TextView rightMsg;
public ViewHolder(View view) {
super(view);
leftLayout = (LinearLayout) view.findViewById(R.id.left_layout);
rightLayout = (LinearLayout) view.findViewById(R.id.right_layout);
leftMsg = (TextView) view.findViewById(R.id.left_msg);
rightMsg = (TextView) view.findViewById(R.id.right_msg);
}
}
public MsgAdapter(List msgList) {
mMsgList = msgList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Msg msg = mMsgList.get(position);
if (msg.getType() == Msg.TYPE_RECEIVED) {
holder.leftLayout.setVisibility(View.VISIBLE);
holder.rightLayout.setVisibility(View.GONE);
holder.leftMsg.setText(msg.getContent());
} else if (msg.getType() == Msg.TYPE_SEND) {
holder.rightLayout.setVisibility(View.VISIBLE);
holder.leftLayout.setVisibility(View.GONE);
holder.rightMsg.setText(msg.getContent());
}
}
@Override
public int getItemCount() {
return mMsgList.size();
}
}
String content = inputText.getText().toString();
if (!"".equals(content)) {
Msg msg = new Msg(content,Msg.TYPE_SEND);
msgList.add(msg);
adapter.notifyItemInserted(msgList.size() - 1);
msgRecyclerview.scrollToPosition(msgList.size() - 1);
inputText.setText("");
}
1.Fragment简单用法
建left和right的xml文件:
建立left和right的类:
public class Left extends Fragment {
@Override
public View onCreateView(LayoutInflater inf, ViewGroup container, Bundle savedInstanceState) {
View view = inf.inflate(R.layout.left,container,false);
return view;
}
}
public class Right1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inf, ViewGroup container, Bundle savedInstanceState) {
View view = inf.inflate(R.layout.right1,container,false);
return view;
}
}
修改activity_main.xml:
动态添加Fragment:
建Right1.xml:
建Right1类:
public class Right1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inf, ViewGroup container, Bundle savedInstanceState) {
View view = inf.inflate(R.layout.right1,container,false);
return view;
}
}
修改activity_main.xml:
修改MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
replaceFragment(new Right());
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
replaceFragment(new Right1());
}
});
}
private void replaceFragment(Fragment fra) {
FragmentManager fraMan = getSupportFragmentManager();
FragmentTransaction tra = fraMan.beginTransaction();
tra.replace(R.id.right_layout,fra);
tra.commit();
}
}
完成。
模拟返回栈:
tra.addToBackStack(null);
活动调用碎片中方法:
Right rigFra = (Right) getFragmentManager().findFragmentById(R.id.right);
碎片调用活动中方法:
在碎片中:
MainActivity act = (MainActivity) getActivity();
同时也可以使用这个方法获取Context。
fragment生命周期:onAttach(),onCreate(),onCreateView(),onActivityCreate(),onStart(),onResume(),onPause(),onStop(),onDestroyView(),onDestroy(),onDetach()
根据设备屏幕大小方向动态选择加载哪个布局:
修改activity_main.xml文件:
在res目录下新建layout_large文件夹,新建名为:activity_main.xml的布局:
最小宽度限定符:
新建layout-sw600dp文件夹,将上面第二个activity_main复制进去。
综合应用——新闻应用:
1。build.gradle 中添加recyclerview支持
2.新建新闻类:News
public class News {
private String title;
private String content;
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getContent(){
return content;
}
public void setContent(String content) {
this.content = content;
}
}
3.新建内容布局文件news_content_frag.xml
4.新建内容布局类NewsContentFragment,继承Fragment:
public class NewsContentFragment extends Fragment {
private View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.news_content_frag,container,false);
return view;
}
public void refresh(String newsTitle,String newsContent) {
View visibilityLayout = view.findViewById(R.id.visibility_layout);
visibilityLayout.setVisibility(View.VISIBLE);
TextView newsTitleText = (TextView)view.findViewById(R.id.news_title);
TextView newsContentText = (TextView)view.findViewById(R.id.news_content);
newsTitleText.setText(newsTitle);
newsContentText.setText(newsContent);
}
}
5.对小屏模式支持,新建Activity:NewsContentAcitivty和相应布局文件news_content.xml:
public class NewsContentActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news_content);
String newsTitle = getIntent().getStringExtra("news_title");
String newsContent = getIntent().getStringExtra("news_content");
NewsContentFragment newsContentFragment = (NewsContentFragment) getSupportFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(newsTitle,newsContent);
}
public static void actionStart(Context context,String newsTitle,String newsContent) {
Intent intent = new Intent(context,NewsContentActivity.class);
intent.putExtra("news_title",newsTitle);
intent.putExtra("new_content",newsContent);
context.startActivity(intent);
}
}
6.新建用于显示新闻列表的布局,news_title_frag.xml:
?xml version="1.0" encoding="utf-8"?>
7.新建news_item.xml作为recyclerview的子布局:
8.新建NewsTitleFragment作为展示新闻列表的碎片:
public class NewsTitleFragment extends Fragment {
private boolean isTwoPane;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.news_title_frag,container,false);
RecyclerView newsTitleRecyclerView = (RecyclerView) view.findViewById(R.id.news_title_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
newsTitleRecyclerView.setLayoutManager(layoutManager);
NewsAdapter adapter = new NewsAdapter(getNews());
newsTitleRecyclerView.setAdapter(adapter);
return view;
}
private List getNews(){
List newsList = new ArrayList<>();
for(int i=1;i<=50;i++) {
News news = new News();
news.setTitle("This is news title" + i);
news.setContent("content" + i);
newsList.add(news);
}
return newsList;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getActivity().findViewById(R.id.news_content_layout) != null) {
isTwoPane = true;
} else {
isTwoPane = false;
}
}
class NewsAdapter extends RecyclerView.Adapter {
private List mNewsList;
class ViewHolder extends RecyclerView.ViewHolder {
TextView newsTitleText;
public ViewHolder(View view) {
super(view);
newsTitleText = (TextView)view.findViewById(R.id.news_title);
}
}
public NewsAdapter(List newsList) {
mNewsList = newsList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item,parent,false);
final ViewHolder holder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
News news = mNewsList.get(holder.getAdapterPosition());
if (isTwoPane) {
NewsContentFragment newsContentFragment = (NewsContentFragment)getFragmentManager().findFragmentById(R.id.news_content_fragment);
newsContentFragment.refresh(news.getTitle(),news.getContent());
news.getContent();
} else {
NewsContentActivity.actionStart(getActivity(),news.getTitle(),news.getContent());
}
}
});
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder,int position) {
News news = mNewsList.get(position);
holder.newsTitleText.setText(news.getTitle());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
}
}
9.修改activity_main.xml:
10.新建layout-sw600dp支持大屏,在此文件夹下新建activity_main:
关于广播
新建广播接收器:
class NetworkChangeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show();
}
}
注册广播接收器:
private IntentFilter mIntentFilter;
private NetworkChangeReceiver mNetworkChangeReceiver;
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
mNetworkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(mNetworkChangeReceiver,mIntentFilter);
静态注册:
发送广播:
Intent intent = new Intent("com.lewanjiang.broadcasttest.MY_BORADCAST");
sendBroadcast(intent);
发送有序广播:
sendOrderedBroadcast(intent);
发送本地广播:
LocalBroadcastManager locBroMan = LocalBroadcastManager.getInstance(this);
Intent int = new Intent("com.lewanjiang.broadcasttest.LOCAL_BROADCAST");
locBroMan.sendBroadcast(int);
注册同普通广播一样,只是注销时:
locBroMan.unregisterReceiver(localReceiver);
强制下线功能实现:
1.新建ActivityCollector类和BaseActivity类:
public class ActivityCollector {
public static List activities = new ArrayList<>();
public static void addActivity(Activity activity) {
activities.add(activity);
}
public static void removeActivity(Activity activity) {
activities.remove(activity);
}
public static void finishAll() {
for (Activity activity:activities) {
if (!activity.isFinishing()) {
activity.finish();
}
}
}
}
public class BaseActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
2.新建一个空的Activity:LoginActivity,修改相应的activity_login.xml和LoginAcitivity:
public class LoginActivity extends BaseActivity {
private EditText accountEdit;
private EditText passwordEdit;
private Button login;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
accountEdit = (EditText) findViewById(R.id.account);
passwordEdit = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if (account.equals("admin") && password.equals("123456")) {
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(LoginActivity.this,"account or password wrong",Toast.LENGTH_SHORT).show();
}
}
});
}
}
3.修改activity_main.xml:
4.修改MainActivity:
public class MainActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button forceOffline = (Button) findViewById(R.id.force_offline);
forceOffline.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.lewanjiang.broadcastbestpractice1.FORCE_OFFLINE");
sendBroadcast(intent);
}
});
}
}
5.注册广播接收器,修改BaseActivity如下:
public class BaseActivity extends AppCompatActivity {
private ForceOfflineReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCollector.addActivity(this);
}
@Override
protected void onResume(){
super.onResume();
IntentFilter intentFilter = new IntentFilter("com.lewanjiang.broadcastbestpractice1.FORCE_OFFLINE");
receiver = new ForceOfflineReceiver();
registerReceiver(receiver,intentFilter);
}
@Override
protected void onPause() {
super.onPause();
if (receiver != null) {
unregisterReceiver(receiver);
receiver=null;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityCollector.removeActivity(this);
}
class ForceOfflineReceiver extends BroadcastReceiver{
@Override
public void onReceive(final Context context, Intent intent) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Warning");
builder.setMessage("You are forced to be offline");
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCollector.finishAll();
Intent intent1 = new Intent(context,LoginActivity.class);
context.startActivity(intent1);
}
});
builder.show();
}
}
}