1 实现两个activity之间的传值
2 利用Handle机制实现多线程
3 实现普通通知,带进度条的通知,带按钮的通知
注:所建工程均为Android 6.0 所以只要是Android 6.0(包括6.0)以上的真机,模拟机都可以使用
1 实现两个activity之间的传值:
顾名思义,要建立两个activity,在运行第一个activity时能打开第二个activity,并且把第二个activity的某项值返回给第一个activity。
这里以“去哪旅行”为例,建立第一个activity——mainactivity.java 界面布局为一个按钮,一个文本框,当点击按钮时能够打开第二个activity,显示可供选择的地点,选择之后把值返回到文本框中,结束。
MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button bn;
EditText city;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bn = (Button) findViewById(R.id.bn);
city = (EditText) findViewById(R.id.city);
Button bn1 = (Button) findViewById(R.id.bn1);
bn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View source) {
Intent intent = new Intent(MainActivity.this, SelectCityActivity.class);
startActivityForResult(intent, 0);
}
});
bn1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
//Intent是一种运行时绑定(run-time binding)机制,它能在程序运行过程中连接两个不同的组件,在存放资源代码的文件夹下下,
Intent i = new Intent(MainActivity.this , HandleActivityDemo.class);
//启动
startActivity(i);
}
});
}
@Override
public void onActivityReenter(int resultCode, Intent data) {
super.onActivityReenter(resultCode, data);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == 0 && (resultCode == 0)) {
Bundle data = intent.getExtras();
String resultCity = data.getString("city");
city.setText(resultCity);
}
}
SelectCittyActivity:
public class SelectCityActivity extends ExpandableListActivity {
private String[] provinces=new String[]{"安徽","江苏","浙江"};
private String[][] cities=new String[][]{
{"合肥","芜湖","马鞍山","阜阳"},
{"南京","宿迁","无锡","苏州"},
{"杭州","金华","宁波","温州"}};
// @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_select_city);
ExpandableListAdapter adapter=new BaseExpandableListAdapter() {
@Override
public int getGroupCount() {
return provinces.length;
}
@Override
public int getChildrenCount(int groupPosition) {
return cities[groupPosition].length;
}
private TextView getTextView(){
AbsListView.LayoutParams lp=new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,64);
TextView textView=new TextView(SelectCityActivity.this);
textView.setLayoutParams(lp);
textView.setGravity(Gravity.CENTER_VERTICAL|Gravity.LEFT);
textView.setPadding(36,0,0,0);
textView.setTextSize(20);
return textView;
}
@Override
public Object getGroup(int groupPosition) {
return provinces[groupPosition];
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return cities[groupPosition][childPosition];
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
LinearLayout ll=new LinearLayout(SelectCityActivity.this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ImageView logo=new ImageView(SelectCityActivity.this);
ll.addView(logo);
TextView textView=getTextView();
textView.setText(getGroup(groupPosition).toString());
ll.addView(textView);
return ll;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
TextView textView=getTextView();
textView.setText(getChild(groupPosition,childPosition).toString());
return textView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
};
setListAdapter(adapter);
getExpandableListView().setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Intent intent=getIntent();
intent.putExtra("city",cities[groupPosition][childPosition]);
SelectCityActivity.this.setResult(0,intent);
SelectCityActivity.this.finish();
return false;
}
});
}
}
activity_main.xml:
HandleActivityDemojava:
public class HandleActivityDemo extends Activity {
ImageView imgchange;
//定义切换的图片的数组id
int [] imgids = new int[]{
R.drawable.s_1, R.drawable.s_2,R.drawable.s_3,
R.drawable.s_4
};
int imgstart = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handle_demo);
final ImageView imgchange = (ImageView) findViewById(R.id.imgchange);
final Handler myHandler = new Handler()
{
@Override
//重写handleMessage方法,根据msg中what的值判断是否执行后续操作
public void handleMessage(Message msg) {
if(msg.what == 0x123)
{
imgchange.setImageResource(imgids[imgstart++ % 4]);
}
}
};
//使用定时器,每隔200毫秒让handler发送一个空信息
new Timer().schedule(new TimerTask() {
@Override
public void run() {
myHandler.sendEmptyMessage(0x123);
}
}, 0,200);
Button bn2=(Button)findViewById(R.id.bn2);
bn2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
//Intent是一种运行时绑定(run-time binding)机制,它能在程序运行过程中连接两个不同的组件,在存放资源代码的文件夹下下,
Intent i = new Intent(HandleActivityDemo.this , NotificationActivityDemo.class);
//启动
startActivity(i);
}
});
}
}
activity_handle_demo.xml:
3 实现普通通知,带进度条的通知,带按钮的通知
NotificationActivityDemo.java:
class NotificationActivityDemo extends AppCompatActivity implements View.OnClickListener {
private Context mContext;
private Button btn_2;
private Button btn_5;
private Button btn_7;
private Notification.Builder notification3;
Bitmap LargeBitmap=null;
/**
* 创建通知渠道
* @param channel_id 渠道id
* @param channel_name 渠道名称
* @param channel_desc 渠道描述
* @param importance 渠道优先级
* @param group_id 渠道组,若没有渠道组,则传null
*/
private String CHANNEL_ID = "my_channel_01";
//用户可见的通知渠道组名称
private String CHANNEL_NAME = "My Notification channel 01";
private String CHANNEL_ID_1 = "my_channel_02";
//用户可见的通知渠道组名称
private String CHANNEL_NAME_1 = "My Notification channel 02";
@RequiresApi(api = Build.VERSION_CODES.O)
private void createNotificationChannel(String channel_id, String channel_name, String channel_desc, int importance, String group_id){
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//配置通知渠道id,渠道名称(用户可以看到),渠道优先级
NotificationChannel mChannel = new NotificationChannel(channel_id, channel_name,importance);
//配置通知渠道的描述
mChannel.setDescription(channel_desc);
//配置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
//配置通知出现时的震动(如果 android 设备支持的话)
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 100, 200});
//配置渠道组
if(group_id!=null){
mChannel.setGroup(group_id);//设置渠道组
}
//在NotificationManager中创建该通知渠道
manager.createNotificationChannel(mChannel);
}
// 通知渠道组的id.
private String group_id = "my_group_01";
//用户可见的通知渠道组名称
private String group_name = "My Notification Group 01";
private String group01_id = "my_group_02";
//用户可见的通知渠道组名称
private String group_name01 = "My Notification Group 02";
@RequiresApi(api = 26)
private void createNotificationChannelGroup() {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannelGroup(new NotificationChannelGroup(group_id, group_name));
manager.createNotificationChannelGroup(new NotificationChannelGroup(group01_id, group_name01));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_demo);
mContext = NotificationActivityDemo.this;
LargeBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.iv_lc_icon);
bindView();
}
private void bindView() {
btn_2 = (Button) findViewById(R.id.btn_2);
btn_5 = (Button) findViewById(R.id.btn_5);
btn_7 = (Button) findViewById(R.id.btn_7);
btn_2.setOnClickListener(this);
btn_5.setOnClickListener(this);
btn_7.setOnClickListener(this);
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_2:
createNotificationChannelGroup();//创建渠道组
createNotificationChannel(CHANNEL_ID,CHANNEL_NAME,"渠道描述",NotificationManager.IMPORTANCE_LOW,group_id);
//添加notification点击后效果
PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID)
.setContentTitle("音乐歌词") //标题
.setContentText("不下雪的广东,不一样的的天空,他们都一样彼此有着破碎的梦,最后消失在人海之中......") //内容
.setSubText("——<<不下雪的广东--广东雨神>>") //内容下面的一小段文字
.setTicker("普通按钮")
.setWhen(System.currentTimeMillis())
.setContentIntent(intent) //设置通知时间
.setSmallIcon(R.mipmap.ic_lol_icon) //设置小图标
.setLargeIcon(LargeBitmap)//设置大图标
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE) //设置默认的三色灯与振动器
// .setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.biaobiao)) //设置自定义的提示音
.setAutoCancel(true)
.setColorized(true)//启用通知的背景颜色
.setColor(Color.RED)//设置通知的背景颜色
.build();
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(1, notification);
break;
case R.id.btn_5:
createNotificationChannelGroup();//创建渠道组
createNotificationChannel(CHANNEL_ID,CHANNEL_NAME,"渠道描述",NotificationManager.IMPORTANCE_LOW,group_id);
PendingIntent intent3 = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
Notification notification2 = new Notification.Builder(getApplicationContext(), CHANNEL_ID)
.setContentTitle("带有操作按钮的通知")
.setContentText("一朝花开傍柳,寻香误觅亭侯,纵饮朝霞半日晖......") //内容
.setSubText("——知否知否,应是绿肥红瘦") .setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(intent3)
.setAutoCancel(true)
.setColorized(true)//启用通知的背景颜色
.setColor(Color.RED)//设置通知的背景颜色
.addAction(R.mipmap.ic_launcher,"确认",intent3)
.addAction(R.mipmap.ic_launcher,"取消",intent3)
.addAction(R.mipmap.ic_launcher,"忽略",intent3)
.build();
NotificationManager manager2 = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager2.notify(2, notification2);
break;
case R.id.btn_7:
createNotificationChannelGroup();//创建渠道组
createNotificationChannel(CHANNEL_ID,CHANNEL_NAME,"渠道描述",NotificationManager.IMPORTANCE_LOW,group_id);
// createNotificationChannelGroup();//创建渠道组
// createNotificationChannel(CHANNEL_ID_1,CHANNEL_NAME_1,"渠道描述",NotificationManager.IMPORTANCE_LOW,group01_id);
PendingIntent intent4 = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
notification3 = new Notification.Builder(getApplicationContext())
.setChannelId(CHANNEL_ID)
.setContentTitle("带有进度条的通知")
.setContentText("正在等待下载")
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(intent4)
.setProgress(100,0,false)
.setAutoCancel(true)
.addAction(R.mipmap.ic_launcher,"关闭",intent4);
NotificationManager manager3 = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager3.notify(3, notification3.build());
new Thread(new Runnable() {
@Override
public void run() {
int x=0;
while (x<100){
x++;
sleep(50);
NotificationManager manager3 = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification3.setChannelId(CHANNEL_ID_1)
.setProgress(100,x,false)
.setContentText(String.format("已下载%d%%",x));
manager3.notify(3, notification3.build());
}
//此处要间隔一段时间再去更新,间隔时间过短的话会导致后面的Notification更新失效
sleep(400);
NotificationManager manager3 = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification3.setProgress(0,0,false)
.setContentText("下载完毕")
.setChannelId(CHANNEL_ID);
manager3.notify(3, notification3.build());
}
}).start();
break;
}
}
public void sleep(int time)
{
try {
Thread.sleep(time);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
activity_notification_demo.xml:
Mainifests.xml:
color.xml:
#008577
#00574B
#D81B60
#009966
#CC0000
#FF99CC
运行截图: