1. 程式人生 > >【跨程序】跨程序通訊---BroadCast(廣播)

【跨程序】跨程序通訊---BroadCast(廣播)

1、AIDL


BroadCast是被動跨程序通訊,只能被動接收訪問。

實際開發中常用來做什麼?

1.監聽簡訊,監聽來電,監聽網路。

2.可以增強APP之間的互動,和使用者粘性。不過個人認為這個很沒必要,增加粘性,最簡單的方法是推送

舉個栗子:兩個程式:A程式和B程式,A傳送廣播,B接收廣播。

1.新建A程式,隨意寫一個點選事件,向B傳送廣播

Intent intent = new Intent("com.wgl.defaultBroadcast");
MainActivity.this.sendBroadcast(intent);
注意:引數"com.wgl.defaultBroadCast"對應B程式的<action/>標籤

A程式的清單配置檔案manifest,不需要任何許可權。

安裝A程式。

2.新建B程式,新建類,起個名字:AcceptBroadCast,繼承BroadCastReceiver

/**
 * 自定義廣播
 * Author:Biligle.
 */
public class AcceptReciver extends BroadcastReceiver {
    private static String ACTION = "com.wgl.defaultBroadcast";
    @Override
    public void onReceive(Context context, Intent intent) {
        //intent.getAction():獲取傳送過來的action)(從A傳送過來的)
        if(intent.getAction().equals(ACTION)){
            Toast.makeText(context,"接到一個廣播!!!",Toast.LENGTH_LONG).show();
        }
    }
}

manifest檔案:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.wgl.share.share">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="com.wgl.share.share.AcceptReciver">
            <intent-filter>
                <action android:name="com.wgl.defaultBroadcast"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>
注意<receiver>標籤裡的action,是自定義的名字,如果需要呼叫系統的簡訊廣播,電話等,可自行百度。
安裝B程式。

3.執行A程式傳送廣播,B成功接收

效果圖:


到這裡,可以自行試寫了。

如果總覺得Toast出一個廣播內容,有點兒low,那麼,接下來加入Service+Notification,後臺提示,好像有點兒推送的意思了。

上乾貨:

A程式不動,修改B程式,如下:

1.新建BackgroundService繼承Service

appName:專案的名字。

data:點選後臺訊息後,跨程序跳轉B程式,Intent intent = new Intent(action,Uri.parse(data))。

public class BackgroundService extends Service {
    private static final int DOWN_OK = 1;
    private String app_name;
    private String data;
    private NotificationManager notificationManager;
    private Notification notification;
    private RemoteViews contentView;

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

    /**
     * 方法描述:onStartCommand方法
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        app_name = intent.getStringExtra("appName");
        data = intent.getStringExtra("data");
        createNotification();
        return super.onStartCommand(intent, flags, startId);
    }



    /**
     * 方法描述:createNotification方法
     */
    @SuppressWarnings("deprecation")
    public void createNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification = new Notification.Builder(BackgroundService.this)
                    .setAutoCancel(true)
                    .setContentTitle(app_name + "點選開啟")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setWhen(System.currentTimeMillis())
                    .build();
        }else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
            Notification.Builder builder = new Notification.Builder(BackgroundService.this)
                    .setAutoCancel(true)
                    .setContentTitle(app_name + "點選開啟")
                    .setContentText("describe")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setWhen(System.currentTimeMillis())
                    .setOngoing(true);
            notification=builder.getNotification();
        }

        notification.flags = Notification.FLAG_ONGOING_EVENT;

        /*** 自定義  Notification 的顯示****/
        contentView = new RemoteViews(getPackageName(),R.layout.notification_item);
        contentView.setTextViewText(R.id.notificationTitle, app_name + "點選開啟");
        notification.contentView = contentView;
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(data));
        //給點選事件加入ID標識,方便跳轉之後刪除通知
        intent.putExtra("notifycationId",R.id.notificationTitle);
        //必須開啟一個新棧
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        //三個引數請自行百度
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this,
                1,
                intent, PendingIntent.FLAG_CANCEL_CURRENT
        );
        //為單獨按鈕新增點選事件
        contentView.setOnClickPendingIntent(R.id.notificationTitle,pendingIntent);
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //注意這裡的R.id.notificationTitle要和intent.putExtra的引數一致
        notificationManager.notify(R.id.notificationTitle, notification);
    }

}

2.在AcceptReceiver裡面,這樣修改:
/**
 * 自定義廣播
 * Author:Biligle.
 */
public class AcceptReciver extends BroadcastReceiver {
    private static String ACTION = "com.wgl.defaultBroadcast";
    @Override
    public void onReceive(Context context, Intent intent) {
        //intent.getAction():獲取傳送過來的action)(從A傳送過來的)
        if(intent.getAction().equals(ACTION)){
//            Toast.makeText(context,"接到一個廣播!!!", Toast.LENGTH_LONG).show();
            Intent i = new Intent(context, BackgroundService.class);
            i.putExtra("appName", "跨程序");
            i.putExtra("data", "content://com.wgl.share:8080/openApp");
            context.startService(i);//開啟後臺服務
        }
    }
}

3.在B程式的OpenActivity裡面

public class OpenActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open);
        int notifycationId = getIntent().getIntExtra("notifycationId",0);
        if(notifycationId != 0){
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.cancel(notifycationId);
        }
    }
}
4.安裝B程式,並執行,效果圖: