2012年12月7日 星期五

String to char array

if(content.toCharArray()[0]=='t'){

content is a string.
.toCharArray() is the function.
[0] Something you know already.

在BroadcastReceiver內使用Internal Storage I/O


//Read in. st. from File"screenoff"
        String fileName = "screenoff";
        int readed;
        String content="";
        byte[] buff = new byte[256]; //input stream buffer
        //Input stream
        try{
        FileInputStream reader = context.getApplicationContext().openFileInput(fileName);
        while((readed = reader.read(buff))!=-1){
         content+=new String(buff).trim();
        }
        }catch(FileNotFoundException e){
        e.printStackTrace();
        }catch (IOException e){
        e.printStackTrace();
        }
        //End of Read in. st. from File"screenoff"

----------------------------------------------------------------------------------------------------
Instead of openFileInput("string.txt"); try usingcontext.getApplicationContext().openFileInput("string.txt");.

Success BroadcastReceiver

MyBroadCastReciever.java
public class MyBroadCastReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("Check","Screen went OFF");
Toast.makeText(context, "screen OFF",Toast.LENGTH_LONG).show();
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("Check","Screen went ON");
Toast.makeText(context, "screen ON",Toast.LENGTH_LONG).show();
}
}
}

MainActivity.java
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
MyBroadCastReciever r = new MyBroadCastReciever();
registerReceiver(r,filter);

IntentFilter filter2 = new IntentFilter(Intent.ACTION_SCREEN_ON);
MyBroadCastReciever r2 = new MyBroadCastReciever();
registerReceiver(r2,filter2);

2012年12月6日 星期四

廣播機制 Broadcast 和BroadReceiver




2011-03-23 16:11:45|  分类: Android |  标签:android  intent  context  import  private   |字号 订阅
1、作用

异步操作、通知
2、两种注册方式
2.1 在AndroidManifest.xml中注册
<receiver android:name="EoeAndroidReceiver">
 <intent-filter>
  <action android:name="com.eoeandroid.action.NEW_BROADCAST" />
 </intent-filter>
</receiver>
2.2 在代码中直接注册
IntentFilter filter = new IntentFilter(NEW_BROADCAST);
EoeAndroidReceiver eoeandroidReceiver = new EoeAndroidReceiver();
registerReceiver(eoeandroidReceiver,filter);

3、注销
unregisterReceiver(eoeandroidReceiver);

4、发送广播

sendBroadcast(intent);

5、接收广播
onReceiver(Context context,Intent intent);

6、示例

6.1 MainActivity.Java

package com.browan.server;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
 private static final int ITEM0 = Menu.FIRST;
 private static final int ITEM1 = Menu.FIRST + 1;

 private static final String ACTION_1 = "com.eoeandroid.action.NEW_BROADCAST1";
 private static final String ACTION_2 = "com.eoeandroid.action.NEW_BROADCAST2";
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);//相关布局模板文件main.xml      
        setTitle("按menu菜单触发测试");
    }
   
    public boolean onCreateOptionsMenu(Menu menu)
    {
     super.onCreateOptionsMenu(menu);
     menu.add(0,ITEM0,0,"显示Notification");
     menu.add(0,ITEM1,0,"消除Notification");
     menu.findItem(ITEM1);
     return true;
    }
   
    public boolean onOptionsItemSelected(MenuItem item)
    {
     switch(item.getItemId())
     {
      case ITEM0:
      actionClickMenuItem1();
      break;
      case ITEM1:
      actionClickMenuItem2();
      break;
     }
     return true;
    }
   
    private void actionClickMenuItem1() {
  // TODO Auto-generated method stub
  Intent intent = new Intent(ACTION_1);
  sendBroadcast(intent);
 }

 private void actionClickMenuItem2() {
  // TODO Auto-generated method stub
  Intent intent = new Intent(ACTION_2);
  sendBroadcast(intent);
 }

}

6.2 EoeAndroidReceiver1.Java

package com.browan.server;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class EoeAndroidReceiver1 extends BroadcastReceiver{
 private static final int NOTIPICATION_ID = 21321;
 Context context;

 @Override
 public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub
  this.context = context;
  showNotification();
 }

 @SuppressWarnings("unused")
 private void showNotification() {
  // TODO Auto-generated method stub
  // 实例化通知管理器
  NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
  // 实例化一个通知,并指定其图标和标题(在提示栏上显示)
  Notification notification = new Notification(R.drawable.icon,"在EoeAndroidReceiver1里",System.currentTimeMillis());
 
  // 指定单击通知后所打开的详细的通知页面(单击通知后打开 NotificationView)
  PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context,MainActivity.class), 0);
  // 设置通知的发送人和通知的详细内容(打开提示栏后在通知列表中显示)
  notification.setLatestEventInfo(context, "通知发送人", "我是详细的通知信息我是详细的通知信息我是详细的通知信息", contentIntent);
  // 发出通知(其中第一个参数为通知标识符)
  notificationManager.notify(getNotipicationId(), notification);
 }

 public static int getNotipicationId() {
  return NOTIPICATION_ID;
 }
}

6.3 EoeAndroidReceiver2.Java

package com.browan.server;

import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class EoeAndroidReceiver2 extends BroadcastReceiver{
 Context context;

 @Override
 public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub
  this.context = context;
  deleteNotification();
 }

 private void deleteNotification() {
  // TODO Auto-generated method stub
  NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
  notificationManager.cancel(EoeAndroidReceiver1.getNotipicationId());
 }
}
6.4 AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.browan.server"
      android:versionCode="1"
      android:versionName="1.0">

 <uses-permission android:name="android.permission.NEW_BROADCAST1" />
 <uses-permission android:name="android.permission.NEW_BROADCAST2" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
               
        <!--注册两个BroadcastReceiver -->
        <receiver android:name="EoeAndroidReceiver1">
   <intent-filter>
    <action android:name="com.eoeandroid.action.NEW_BROADCAST1" />
   </intent-filter>
  </receiver>
 
     <receiver android:name="EoeAndroidReceiver2">
   <intent-filter>
    <action android:name="com.eoeandroid.action.NEW_BROADCAST2" />
   </intent-filter>
  </receiver>
    </application>
</manifest>

2012年12月5日 星期三

android短信监听(ZZ)



(2010-08-06 15:10:13)
转载
标签:
it
分类: 知识收藏
接收短信也是比较方便的,主要是继承BroadcaseReceiver 类 ,覆盖onReceive 函数:

1:相关类:
android.content.BroadcastReceiver
android.telephony.gsm.SmsMessage;

2:example code.

public class MessageDemo extends BroadcastReceiver {
    private static final String strACT = "android.provider.Telephony.SMS_RECEIVED";

public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(strACT)) {
StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] msg = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
for (SmsMessage currMsg : msg) {
sb.append("From:");
sb.append(currMsg.getDisplayOriginatingAddress());
sb.append("\nMessage:");
sb.append(currMsg.getDisplayMessageBody());
}
}
}

}
}
3: 相关的配置

修改AndroidManifest.xml,在Activity下添加receiver节点:
<receiver android:name="MessageDemo">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
随后在application下添加节点:
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

4:使用BroadReceiver的弊端
查看BroadReceiver sdk reference , 可以了解到所有的BroadReceiver对短信的接收是无顺序的状态,即使是使用了Ordered broadcasts对于同等优先级别的BroadReceiver ,也会产生无顺序的行为。
所以下面介绍另一种接收短信的行为,包括其中可以进行短信的删除。

5:从数据库端监听sms的收发
//如下 主要用于内部数据库改变,向外面的界面(Activity)做反应
class SMSHandler extends Handler
{
    public void handleMessage(Message msg)
    {
        //Handle message
    }
}

// 对收到短消息后,做出的处理,这里直接删除,并没有反应到界面,所以上面的handleMessage是空的。
class SMSObserver extends ContentObserver
{
    private Handle m_handle = null;

    public SMSObserver(Handle handle)
    {
        super(handle);
        m_handle = handle;
    }

    public void onChange(boolean bSelfChange)
    {
        super.onChange(bSelfChange);

        //Send message to Activity
        Message msg = new Message();
        msg.obj = "xxxxxxxxxx";
        m_handle.sendMessage(msg);

String strUriInbox = "content://sms/inbox";
Uri uriSms = Uri.parse(strUriInbox);  //If you want to access all SMS, just replace the uri string to "content://sms/"
Cursor c = mContext.getContentResolver().query(uriSms, null, null, null, null);
// delete all sms here when every new sms occures.
while (c.moveToNext())
{  
       //Read the contents of the SMS;
       for(int i; i < c.getColumnCount(); i++)
        {
            String strColumnName = c.getColumnName(i);
            String strColumnValue = c.getString(i);
        }


       //Delete the SMS
        String pid = c.getString(1);  //Get thread id;
       String uri = "content://sms/conversations/" + pid;
       mContext.getContentResolver().delete(Uri.parse(uri), null, null);      
 
}

       


    }
}

//把基本类功能性地应用起来
ContentResolver contentResolver = getContentResolver();// Context 环境下getContentResolver()
Handler handler = new SMSHandler();
ContentObserver m_SMSObserver = new SMSObserver(handler);
contentResolver.registerContentObserver(Uri.parse("content://sms/inbox"),true, m_SMSObserver);
//Register to observe SMS in outbox,we can observe SMS in other location by changing Uri string, such as inbox, sent, draft, outbox, etc.)

// some Available Uri string  for sms.


REMEBER: must request following permission
1) Read SMS
    <uses-permssion android:name="android.permission.READ_SMS" />
2) Delete/Modify/Send SMS
    <uses-permssion android:name="android.permission.WRITE_SMS" />
in AndroidManifest.xml

2012年12月2日 星期日

Android Code Producer 0.3

下載: https://docs.google.com/file/d/0B6sL60kI5J0md05nWGtBbTFtbHM/edit
(進入上面網址後按"檔案>下載")

Doc Folder root: https://docs.google.com/folder/d/0B6sL60kI5J0mTno0S3J0bm1qY0U/edit

消息模式Toast.makeText用法


Toast用于向用户显示一些帮助/提示。下面我做了5中效果,来说明Toast的强大,定义一个属于你自己的Toast。
1.默认效果

代码
Toast.makeText(getApplicationContext(), "默认Toast样式",
     Toast.LENGTH_SHORT).show();
2.自定义显示位置效果

代码
toast = Toast.makeText(getApplicationContext(),
     "自定义位置Toast", Toast.LENGTH_LONG);
   toast.setGravity(Gravity.CENTER, 0, 0);
   toast.show();
3.带图片效果

代码
toast = Toast.makeText(getApplicationContext(),
     "带图片的Toast", Toast.LENGTH_LONG);
   toast.setGravity(Gravity.CENTER, 0, 0);
   LinearLayout toastView = (LinearLayout) toast.getView();
   ImageView imageCodeProject = new ImageView(getApplicationContext());
   imageCodeProject.setImageResource(R.drawable.icon);
   toastView.addView(imageCodeProject, 0);
   toast.show();
4.完全自定义效果

代码
LayoutInflater inflater = getLayoutInflater();
   View layout = inflater.inflate(R.layout.custom,
     (ViewGroup) findViewById(R.id.llToast));
   ImageView image = (ImageView) layout
     .findViewById(R.id.tvImageToast);
   image.setImageResource(R.drawable.icon);
   TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
   title.setText("Attention");
   TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
   text.setText("完全自定义Toast");
   toast = new Toast(getApplicationContext());
   toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
   toast.setDuration(Toast.LENGTH_LONG);
   toast.setView(layout);
   toast.show();
5.其他线程

 代码
new Thread(new Runnable() {
    public void run() {
     showToast();
    }
   }).start();
Related Posts Plugin for WordPress, Blogger...