Notification
- 设置Notification内容
//创建Builder,设置Notification内容
NotificationCompat.Builder builder=new NotificationC
ompat.Builder(this);
//必须设置以下内容
builder.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Music Title")
.setContentText("content");
- 设置点击通知启动Activity
Intent intent=new Intent(context,MainActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity (context,0,intent,0);
mBuilder.setContentIntent(pendingIntent);
- 更新通知
Notification notification= builder.build();
NotificationManager manager= (NotificationManager) getSy
stemService(NOTIFICATION_SERVICE);
manager.notify(001,notification);
- 自定义通知布局
使用RemoteView布局,通过发送广播来更新RemoteView
RemoteViews rmViews=new RemoteViews(context.getPackageNa
me(), R.layout.notification_layout);
rmViews.setTextViewText(R.id.notify_music_name,title);
//使用setContent(remoteView)通知高度会被限制
mBuilder.setCustomBigContentView(remoteViews);
服务中使用进程
使用进程的步骤
- Manifasts中注册
android:process
- 绑定服务
- 使用Handler,Mesenger或AIDL传递数据
- Manifasts中注册
使用Messenger
在ServiceonBinder()
方法返回Messenger
public IBinder onBind(Intent intent) {
//使用Service中的Handler创建Messenger
serviceMessenger=new Messenger(mHandler);
return serviceMessenger.getBinder();
}
Activity中取回Messenger
private ServiceConnection mConnection=new ServiceConnect
ion() {
@Override
public void onServiceConnected(ComponentName name, I
Binder service) {
serviceMessenger = new Messenger(service);
updateSavedItems();
}...
使用Messenger发送消息
Message msg=mHandler.obtainMessage();
msg.what=1;
Bundle bundle=new Bundle();
bundle.putString("PATH",path);
//跨进程传递的对象需要实现Parcelable接口
msg.obj=bundle;
msg.replyTo=activityMessenger;
try {
//发送消息到Service
serviceMessenger.send(msg);
} catch (RemoteException e) {
e.printStackTrace();
Log.d("MainActivity","activity发送消息失败");
}
使用AIDL
使用步骤
- 在项目的src/main文件夹下创建AIDL文件,
- AndroidStudio会自动生成继承于Binder的抽象类
Stub
- 创建
Stub
并重写里面的方法 - 通过
onBinder()
传递Stub
对象
创建.aidl文件
使用Java语言编写,定义接口和方法签名
AIDL默认支持的数据类型(参考google官方文档):- 基本数据类型(int,long,float,boolean,等)
- String
- CharSequence
- List
- Map
默认不支持的对象需要实现
Parcelable
接口并在.aidl文件中import
package com.example.chao.aidltest;
// Declare any non-default types here with import statements
//导入文件
import com.example.chao.aidltest.Student;
interface IMyAidlInterface {
void basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat,double aDouble, String aString);
//定义接口,Student对象已经实现Parcelable接口
String studentInfo(Student s);
}