注意我们要在清单文件中注册Service
<service Android:name=".PushSmsService"></service>
由于通知信息使用到了手机的震动功能和网络访问,所以需要配置权限
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
我们再定义一个Activity,用于用户点击下拉通知栏里的某条消息后,跳转到详细的消息界面
public class ContentActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
Intent intent = getIntent();
TextView tv_content = (TextView) this.findViewById(R.id.tv_content);
TextView tv_number = (TextView) this.findViewById(R.id.tv_number);
TextView tv_date = (TextView) this.findViewById(R.id.tv_date);
if (intent != null) {
String content = intent.getStringExtra("content");
String number = intent.getStringExtra("number");
String date = intent.getStringExtra("date");
tv_content.setText("内容:" + content);
tv_number.setText("号码:" + number);
tv_date.setText("日期:" + date);
}
}
}
同样,我们需要在清单文件中注册新的Activity
<activity android:name=".ContentActivity"></activity>
注意到上边的代码是需要服务器提供支持的,我们去新建一个简单的服务器,里边添加一个Servlet和一个实体类就可以了
public class PushSmsServlet extends HttpServlet {
private static int index = 1;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(index);
// List<Sms> smsList = new ArrayList<Sms>();
Sms sms = new Sms(index,
"我爱你我爱你我爱你我爱你我爱你我爱你我爱你我爱你我爱你我爱你我爱你我爱你" + index, "2013-03-03",
"13522224444");
index++;
// smsList.add(sms);
// sms = new Sms(0, "我真的爱你", "2013-04-04", "13522224444");
// smsList.add(sms);
// sms = new Sms(1, "我真的真的爱你", "2013-05-05", "13522224444");
// smsList.add(sms);
response.setContentType("text/html");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
Gson gson = new Gson();
// 将Sms类的数据转换为json数据格式
String json = gson.toJson(sms);
out.write(json);
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
再定义封装用于存放消息的类
public class Sms {
private int state;
private String content;
private String date;
private String number;
public Sms(int state, String content, String date, String number) {
super();
this.state = state;
this.content = content;
this.date = date;
this.number = number;
}
}
