【跨進程】跨進程通信---BroadCast(廣播)

1、AIDL

2、BroadCast

3、Activity


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程序,並運行,效果圖:






發佈了80 篇原創文章 · 獲贊 65 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章