Extending AIR for Android (2)

System Notifications and Services

AIR for Android applications don’t yet have an API to do Android system notifications. But you can add system notifications to your AIR for Android application through a startup hook. In order for the AIR application to communicate with the native Android APIs you must provide a bridge for the communication. The simplest way to create that bridge is using a network socket. The Android application can listen for data on the socket and then read that data and determine if it needs to display a system notification. Then the AIR application can connect to the socket and send the necessary data. This is a pretty straightforward example but some security (for instance a key exchange) should be implemented to insure that malicious apps don’t discover and abuse the socket. Also some logic to determine which socket should be used would likely be necessary.

Inside the application section add a new Android Service:

   <service android:enabled="true" android:name="TestService" />

Since this example uses a Socket you will also need to add the INTERNET permission:

   <uses-permission android:name="android.permission.INTERNET"/>

You might also want to enable the phone to vibrate when there is a new notification. If so add that permission as well:

   <uses-permission android:name="android.permission.VIBRATE"/>

Save your changes to AndroidManifest.xml.

Next, create the background Java Service class, called TestService. This service will listen on a socket and when necessary, display an Android Notification:

package com.jamesward;   
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;   
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;   

public class TestService extends Service {  
    private boolean stopped=false;  
 private Thread serverThread;  
 private ServerSocket ss;     

 @Override 
 public IBinder onBind(Intent intent){ 
       return null;  
 }     

 @Override  public void onCreate()   {
        super.onCreate();       
  Log.d(getClass().getSimpleName(), "onCreate");         

  serverThread = new Thread(new Runnable() {           
         public void run()  {                
           try  {                        
         Looper.prepare();                        
      ss = new ServerSocket(12345);                        
      ss.setReuseAddress(true);                        
      ss.setPerformancePreferences(100, 100, 1);                        

      while (!stopped)   {   
          Socket accept = ss.accept();                                
       accept.setPerformancePreferences(10, 100, 1);                                
       accept.setKeepAlive(true);                                   
       DataInputStream _in = null;                                

       try   {                                        
           _in = new DataInputStream(new BufferedInputStream(accept.getInputStream(),1024));  
       }  catch (IOException e2)  {                                  
           e2.printStackTrace();                                
       }                                   

       int method =_in.readInt();                                   
       switch (method) {                                  
        // notification                                  
        case 1: 
            doNotification(_in);
         break;                                
          }                        
      }                
     }   catch (Throwable e)  {                        
         e.printStackTrace();                        
      Log.e(getClass().getSimpleName(), "Error in Listener",e);                
     }                   

     try {                  
         ss.close();                
     }  catch (IOException e)  {                  
         Log.e(getClass().getSimpleName(), "keep it simple");                
     }        
    }           
   },"Server thread");      

  serverThread.start();     
 }     

 private void doNotification(DataInputStream in) throws IOException {    
      String id = in.readUTF();    
   displayNotification(id);  
    }     

 @Override 
 public void onDestroy() {          
    stopped=true;          
    try {                  
       ss.close();          
    } catch (IOException e) {}          

    serverThread.interrupt();          

    try {                  
       serverThread.join();          
    } catch (InterruptedException e) {}  
 }     

 public void displayNotification(String notificationString)   {    
     int icon = R.drawable.mp_warning_32x32_n;    
  CharSequence tickerText = notificationString;    
  long when = System.currentTimeMillis();    
  Context context = getApplicationContext();    
  CharSequence contentTitle = notificationString;    
  CharSequence contentText = "Hello World!";       
  Intent notificationIntent = new Intent(this, MainApp.class);    
  PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);       
  Notification notification = new Notification(icon, tickerText, when);    
  notification.vibrate = new long[] {0,100,200,300};       
  notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);       
  String ns = Context.NOTIFICATION_SERVICE;    

  NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);       
  mNotificationManager.notify(1, notification);  
 }   
}

This service listens on port 12345. When it receives some data it checks if the first “int” sent is “1”. If so, it then creates a new notification using the next piece of data (a string) that is received over the socket.

Modify the MainApp Java class to start the service when the onCreate() method is called:

@Override   
public void onCreate(Bundle savedInstanceState) {        
   try {            
      Intent srv = new Intent(this, TestService.class);            
   startService(srv);        
   }  catch (Exception e)  {            
     // service could not be started        
   }           

   super.onCreate(savedInstanceState);    
}

That is all you need to do in the Android application.

Next, create a Flex application that will connect to the socket and send the right data. Here is some sample code for my Notifier.mxml class, which I used to test the Android service:

  <?xml version="1.0" encoding="utf-8"?><s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"  xmlns:s="library://ns.adobe.com/flex/spark">   
     <fx:Style>    @namespace s "library://ns.adobe.com/flex/spark";    
            global {  fontSize: 32;   } 
     </fx:Style>  

     <s:layout>   
         <s:VerticalLayout horizontalAlign="center" paddingTop="20"/>  
     </s:layout>   

     <s:TextInput id="t" text="test test"/>   
     <s:Button label="create notification">  

     <s:click>   
       <![CDATA[        
              var s:Socket = new Socket();       
              s.connect("localhost", 12345);       
              s.addEventListener(Event.CONNECT, function(event:Event):void {         
                                             trace('connected!');          
                                             (event.currentTarget as Socket).writeInt(1);         
                                             (event.currentTarget as Socket).writeUTF(t.text);         
                                             (event.currentTarget as Socket).flush();         
                                             (event.currentTarget as Socket).close();        });      

               s.addEventListener(IOErrorEvent.IO_ERROR, function(event:IOErrorEvent):void {      
                                               trace('error! ' + event.errorID);        });      

               s.addEventListener(ProgressEvent.SOCKET_DATA, function(event:ProgressEvent):void {        
                                               trace('progress ');        });    

            ]]>   

     </s:click>  

     </s:Button>

    </s:Application>

As you can see there is just a TextInput control that allows the user to enter some text. Then when the user clicks the Button the AIR for Android application connects to a local socket on port 12345, writes an int with the value of 1, writes the string that the user typed into the TextInput control, and finally flushes and closes the connection. This causes the notification to be displayed.

Now simply compile the Flex app and overwrite the assets/app.swf file with the new Flex application. Check out a video demonstration of this code.

原文作者:james ward

本文原始链接:http://blog.zhourunsheng.com/2011/07/extending-air-for-android-2/(迁移后固定链接原样保留)

加入讨论

新评论 — 条

评论保存在本站自托管服务里,无需注册登录,填个昵称就能留言;不依赖任何第三方 Cookie 或账号。请尽量说点有用的 :)