Android基础之通知的使用

今天一切还算OK吧,家里购置了一个网络机顶盒,回来测试一下,效果还不错,下午抽了点时间去给哥哥修电脑,原来

是由于哥哥的调皮儿子老是强制关机导致配置文件丢失,所以电脑崩溃,一开始没有进PE去安装系统,老是卡在一个很奇怪的界面,

最后进入PE之后,选择安装到C盘,问题解决,又Get了一项新技能!!!好了,下面开始说安卓的学习!!!

今天其实主要是通知部分的实战,代码难度有点高,其实也没要都懂,之所以全部敲出来是为了以后拿过来直接用。

一、使用通知

 通知的使用:当某个应用程序希望向用户发出一些提示信息,而该 应用程序又不在前台运行,就可以借助通知实现。
  发出一条通知以后,手机最上方的状态栏会显示一个通知的图标  下拉状态栏后会显示一个通知的图标
  创建通知的一般步骤:
  1.首先需要一个NotificationManager来对通知进行管理,
  可以调用getSystemService()方法来获得。getSystemService()方法
  接收一个字符串参数用于确定获取系统的那个服务。
  2.创建一个Motification对象,这个对象用于存储通知所需的各种信息,
  我们可以使用它的有参构造函数来进行创建
  3.设定通知的布局
  4.最后调用notify()方法将通知显示出来。

部分代码如下:

public class MainActivity extends ActionBarActivity implements OnClickListener {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.send_notice);
// 发送通知的点击事件只能实现监听的接口
button.setOnClickListener(this);
}


public void onClick(View v) {
switch (v.getId()) {


case R.id.send_notice:
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// 状态栏显示的内容
Notification notification = new Notification(
R.drawable.ic_launcher, "This is ticker text",
System.currentTimeMillis());
// setLatestEventInfo是给通知设置一个标准布局


Intent intent = new Intent(this, NotificationActivity.class);
// getActivity是指去获取一个活动的意思,还有getBraodcast、getService
// 第四个参数用于确定pendingIntent的行为
/**
* FLAG_CANCEL_CURRENT:如果该PendingIntent已经存在,则在生成新的之前取消当前的。
* FLAG_NO_CREATE:如果该PendingIntent不存在,直接返回null而不是创建一个PendingIntent.
* FLAG_ONE_SHOT:该PendingIntent只能用一次,在send()方法执行后,自动取消。
* FLAG_UPDATE_CURRENT:如果该PendingIntent已经存在,则用新传入的Intent更新当前的数据。
*/

//构造意图构造延迟意图实例
PendingIntent pi = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
//将延迟意图写入布局
notification.setLatestEventInfo(this, "This is content title",
"This is content text", pi);
//设置消息的提示方式,这里采用默认的提示方式
notification.defaults=Notification.DEFAULT_ALL;
manager.notify(1, notification);
break;
default:
break;
}
}
}

最后不要忘记对通知进行取消,否则即使我们查看了通知,通知还会显示在状态栏,只有彻底销毁活动的时候,通知才会消失。

public class NotificationActivity extends Activity {
//为通知添加以下响应,即当我们点击通知时,显示一部分内容

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_layout);
//取消通知,这样的话只要将通知点击开之后状态栏的标志就会自动消失,而不用等到从后台去销毁活动。
//NotificationManager对活动进行管理
NotificationManager notificationManager=(NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(1);
}
}

二、短信的收发项目

代码如下:

public class MainActivity extends ActionBarActivity {
private TextView sender;
private TextView content;
private EditText to;
private EditText msgInput;
private Button send;
private IntentFilter receiverFilter;
private MessageReceiver messageReceiver;
private IntentFilter sendFilter;
private SendStatusReceiver sendStatusReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sender=(TextView)findViewById(R.id.sender);
        content=(TextView)findViewById(R.id.content);
        //对接收短信广播进行动态注册
        receiverFilter=new IntentFilter();
        receiverFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        messageReceiver=new MessageReceiver();
        registerReceiver(messageReceiver, receiverFilter);
        //对接收短信发送情况进行广播进行注册
        sendFilter=new IntentFilter();
        sendFilter.addAction("SENT_SMS_ACTION");
        sendStatusReceiver=new SendStatusReceiver();
        registerReceiver(sendStatusReceiver, sendFilter);
        //发送信息
        to=(EditText)findViewById(R.id.to);
        msgInput=(EditText)findViewById(R.id.msg_input);
        send=(Button)findViewById(R.id.send);
        send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SmsManager smsManager=SmsManager.getDefault();
Intent sentIntent=new Intent("SENT_SMS_ACTION");
PendingIntent pi=PendingIntent.getBroadcast(MainActivity.this, 0, sentIntent, 0);
smsManager.sendTextMessage(to.getText().toString(), null, msgInput.getText().toString(),pi, null);
}
});
    }
    protected void onDestroy()
    {
    super.onDestroy();
    unregisterReceiver(messageReceiver);
    }
    class MessageReceiver extends BroadcastReceiver {
        
    public void onReceive(Context context, Intent intent) {
    Bundle bundle=intent.getExtras();
    Object []pdus=(Object[])bundle.get("pdus");//提取短信消息
    SmsMessage[] messages=new SmsMessage[pdus.length];
    for(int i=0;i<messages.length;i++)
    {
    messages[i]=SmsMessage.createFromPdu((byte[])pdus[i]);
    }
    String address=messages[0].getOriginatingAddress();//获取发送方号码
    String fullMessage="";
    for(SmsMessage message:messages)
    {
    fullMessage+=message.getMessageBody();//获取短信内容
    }
    sender.setText(address);
    content.setText(fullMessage);
    }
   
    }
    class SendStatusReceiver extends BroadcastReceiver
    {
  //实现了对于短信是否发送成功的广播监听

public void onReceive(Context context, Intent intent) {
if(getResultCode()==RESULT_OK)
{
Toast.makeText(context, "短信发送成功", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "短信发送失败", Toast.LENGTH_SHORT).show();
}
}
   
    }
}

三、调用手机摄像头和相册

public class MainActivity extends ActionBarActivity {
public static final int TAKE_PHOTO = 1;
public static final int CROP_PHOTO = 2;
public static final int CHOOSE_PHOTO = 3;
private Button takePhoto;
private ImageView picture;
private Button chooseFromAlbum;
private Uri imageUri;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//空指针异常有可能是没有find按钮
//注意查看日志时候的Cause by
takePhoto = (Button) findViewById(R.id.take_photo);
picture = (ImageView) findViewById(R.id.picture);
chooseFromAlbum=(Button)findViewById(R.id.choose_from_album);
takePhoto.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// 创建File对象,用于存储拍照后的照片
File outputImage = new File(Environment
.getExternalStorageDirectory(), "output_image.jpg");
if (outputImage.exists()) {
outputImage.delete();
}
try {
outputImage.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);
}
});
chooseFromAlbum.setOnClickListener(new OnClickListener() {


public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
          intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, CHOOSE_PHOTO);// 打开相册


}
});
}


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CROP_PHOTO);// 启动裁剪程序
}
break;
case CROP_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitmap = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
imageUri));
picture.setImageBitmap(bitmap);// 将裁减后的照片显示出来


} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
case CHOOSE_PHOTO:
if (resultCode == RESULT_OK) {
if (Build.VERSION.SDK_INT >= 19) {// 判断手机版本号
handleImageOnKitKat(data);
} else {
handleImageBeforeKitKat(data);
}
}
break;
default:
break;
}
}


@TargetApi(19)
  private void handleImageOnKitKat(Intent data) {
  String imagePath = null;
  Uri uri = data.getData();
  if (DocumentsContract.isDocumentUri(this, uri)) {
   //如果是document类型的Uri,则通过document id处理
  String docId = DocumentsContract.getDocumentId(uri);
  if ("com.android.providers.media.documents".equals(uri
  .getAuthority())) {
  String id = docId.split(":")[1];
  String selection = MediaStore.Images.Media._ID + "=" + id;
  imagePath = getImagePath(
  MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
  } else if ("com.android.providers.media.downloads.documents"
  .equals(uri.getAuthority())) {
  Uri contentUri = ContentUris.withAppendedId(
  Uri.parse("content: downloads/public_downloads"),
  Long.valueOf(docId));
  imagePath = getImagePath(contentUri, null);
  }
  } else if ("content".equalsIgnoreCase(uri.getScheme())) {
  // 如果不是document类型的Uri,则使用普通方式处理
  imagePath = getImagePath(uri, null);
  }
  displayImage(imagePath);
  }
 
  private void handleImageBeforeKitKat(Intent data) {
  Uri uri = data.getData();
  String imagePath = getImagePath(uri, null);
  displayImage(imagePath);
  }
 
  private String getImagePath(Uri uri, String selection) {
  String path = null;
   //通过Uri和selection来获取真实的图片信息
  Cursor cursor = getContentResolver().query(uri, null, selection, null,
  null);
  if (cursor != null) {
  if (cursor.moveToFirst()) {
  path = cursor.getString(cursor.getColumnIndex(Media.DATA));
  }
  cursor.close();
  }
  return path;
  }
 
  private void displayImage(String imagePath) {
  if (imagePath != null) {
  Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
  picture.setImageBitmap(bitmap);
  } else {
  Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT)
  .show();
  }
  }
}

在这个程序中调试时出现了空指针的异常错误,学会查看日志文件,去寻找Cause By,最终原因是由于

没有获取控件的实例,由于这属于编译时异常,所以系统不会提示错误,以后一定要注意!!!

四、播放音频

public class MainActivity extends ActionBarActivity implements OnClickListener{
private Button play;
private Button pause;
private Button stop;
private MediaPlayer mediaPlayer=new MediaPlayer();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play=(Button)findViewById(R.id.play);
        pause=(Button)findViewById(R.id.pause);
        stop=(Button)findViewById(R.id.stop);
        play.setOnClickListener(this);
        stop.setOnClickListener(this);
        pause.setOnClickListener(this);
        initMediaPlayer();
    }
    private void initMediaPlayer()
    {
    try {
    File file=new File(Environment.getExternalStorageDirectory(),"music.mp3");
    //指定音频文件的路径
mediaPlayer.setDataSource(file.getPath());
//让MediaPlayer进入准备状态
mediaPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
   
    }
    //实现接口这种方法比较简单
    public void onClick(View v)
    {
    switch (v.getId()) {
case R.id.play:
if(!mediaPlayer.isPlaying())
mediaPlayer.start();//开始播放
break;
case R.id.pause:
if(mediaPlayer.isPlaying())
mediaPlayer.pause();
break;
case R.id.stop:
if(mediaPlayer.isPlaying())
{
mediaPlayer.reset();//回到起点
initMediaPlayer();
}
break;
default:
break;
}
    }
    protected void onDestroy()
    {
    super.onDestroy();
    if(mediaPlayer!=null)
    {
    mediaPlayer.stop();
    mediaPlayer.release();
    }
    }
}

五、播放视频

public class MainActivity extends ActionBarActivity implements OnClickListener{
private VideoView videoView;
private Button play;
private Button pause;
private Button replay;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        play=(Button)findViewById(R.id.play);
        pause=(Button)findViewById(R.id.pause);
        replay=(Button)findViewById(R.id.stop);
        videoView=(VideoView)findViewById(R.id.video_view);
        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        replay.setOnClickListener(this);
        initVideoPath();
    }
    
    private void initVideoPath()
    {
    File file=new File(Environment.getExternalStorageDirectory(),"测试视频.3gp");
    videoView.setVideoPath(file.getPath());//指定文件路径
    }
    public void onClick(View v)
    {
    switch (v.getId()) {
case R.id.play:
if(!videoView.isPlaying())
videoView.start();
break;
case R.id.pause:
if(videoView.isPlaying())
videoView.pause();
break;
case R.id.stop:
if(videoView.isPlaying())
videoView.resume();
break;
default:
break;
}
    }
    protected void onDestroy()
    {
    super.onDestroy();
    if(videoView!=null)
    videoView.suspend();
    }
}

好了,这就是所学的项目,留着自己慢慢研究,今天时间有点早,明天姥爷生日,happy一下,明天加油,晚安!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值