Android搶紅包助手開發全攻略_Android

來源:互聯網
上載者:User

背景:新年之際,微信微博支付寶紅包是到處飛,但是,自己的手速總是比別人慢一點最後導致紅包沒搶到,紅包助手就應運而生。
需求:收到紅包的時候進行提醒,然後跳轉到紅包的介面方便使用者。
思路:擷取“讀取通知資訊”許可權,然後開啟服務監控系統通知,判斷如果是微信紅包就進行提醒(聲音),然後跳轉到紅包所在的地方。 
介面:

介面分為兩部分,一部分是可以對App進行操作的,下面是一個可以滑動的介面,提示使用者如何是軟體正常工作,布局代碼如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout android:id="@+id/root" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="5dp" android:orientation="vertical" tools:context="com.fndroid.administrator.justforyou.MainActivity"> <LinearLayout  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:orientation="horizontal">  <TextView   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:layout_weight="3"   android:text="開啟提示音"/>  <CheckBox   android:id="@+id/isMusic"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/> </LinearLayout> <LinearLayout  android:layout_width="match_parent"  android:layout_height="wrap_content">  <TextView   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:layout_gravity="center"   android:text="音量大小"/>  <SeekBar   android:id="@+id/seekbar"   android:layout_width="wrap_content"   android:layout_height="wrap_content"   android:layout_gravity="center"   android:layout_weight="1"/> </LinearLayout> <LinearLayout  android:layout_width="match_parent"  android:layout_height="wrap_content"  android:orientation="horizontal">  <TextView   android:layout_width="0dp"   android:layout_height="wrap_content"   android:layout_weight="3"   android:text="有紅包亮屏並解鎖"/>  <CheckBox   android:id="@+id/isUnlock"   android:layout_width="wrap_content"   android:layout_height="wrap_content"/> </LinearLayout> <Button  android:id="@+id/setPermision"  android:layout_width="wrap_content"  android:layout_height="wrap_content"  android:layout_gravity="center"  android:text="設定通知許可權"/> <ScrollView  android:layout_width="match_parent"  android:layout_height="match_parent">  <LinearLayout   android:layout_width="match_parent"   android:layout_height="match_parent"   android:orientation="vertical">   <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_marginTop="10dp"    android:text="聲明:"/>   <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="本軟體為個人開發所得,只能對微信紅包進行提醒。請合理使用本軟體,使用不當造成的各種行為均與本人無關。軟體使用過程不連網,不存在任何盜竊使用者資訊行為,請放心使用。"/>   <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_marginTop="10dp"    android:text="使用方法:"/>   <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="①如果未賦予軟體讀取通知許可權,點擊按鈕“設定通知許可權"/>   <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="②在本軟體右側勾選上,並確認提示資訊"/>   <ImageView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:scaleType="fitCenter"    android:src="@drawable/inf"/>   <TextView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:text="③關閉微信群的訊息免打擾(取消圖中的綠色按鈕)"/>   <ImageView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:src="@drawable/inf2"/>  </LinearLayout> </ScrollView></LinearLayout> 

app開啟的時候開啟一個服務,編寫一個NotificationListenerService的子類並實現onNotificationPosted和onNotificationRemoved方法,前面的方法會在收到通知的時候調用 

// 編寫一個NotificationListenerService的子類並實現onNotificationPosted和onNotificationRemoved方法// 這兩個方法在從SDK版本21的時候開始變成了非抽象,不重寫則不能相容21以下裝置public class NotificationService extends NotificationListenerService { private KeyguardManager.KeyguardLock kl; @Override public void onNotificationPosted(StatusBarNotification sbn) {  // 主介面設定的資訊儲存在SharedPreferences中,在這裡進行擷取  SharedPreferences sharedPreferences = getSharedPreferences("userdata", MODE_PRIVATE);  // 判斷訊息是否為微信紅包  if (sbn.getNotification().tickerText.toString().contains("[微信紅包]") && sbn.getPackageName    ().equals("com.tencent.mm")) {   // 讀取設定資訊,判斷是否該點亮螢幕並解開鎖屏,解鎖的原理是把鎖屏關閉掉   if (sharedPreferences.getBoolean("isUnlock",true)) {    KeyguardManager km = (KeyguardManager) getSystemService(getApplicationContext()      .KEYGUARD_SERVICE);    kl = km.newKeyguardLock("unlock");    // 把系統鎖屏暫時關閉    kl.disableKeyguard();    PowerManager pm = (PowerManager) getSystemService(getApplicationContext()      .POWER_SERVICE);    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |      PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");    wl.acquire();    wl.release();   }   try {    // 開啟notification所對應的pendingintent    sbn.getNotification().contentIntent.send();   } catch (PendingIntent.CanceledException e) {    e.printStackTrace();   }   // 判斷是否該播放提示音   if (sharedPreferences.getBoolean("isMusic",true)){    MediaPlayer mediaPlayer = new MediaPlayer().create(this, R.raw.heihei);    mediaPlayer.start();   }   // 這裡監聽一下系統廣播,判斷如果螢幕熄滅就把系統鎖屏還原   IntentFilter intentFilter = new IntentFilter();   intentFilter.addAction("android.intent.action.SCREEN_OFF");   ScreenOffReceiver screenOffReceiver = new ScreenOffReceiver();   registerReceiver(screenOffReceiver, intentFilter);  } } class ScreenOffReceiver extends BroadcastReceiver {  @Override  public void onReceive(Context context, Intent intent) {   if (kl != null) {    // 還原鎖屏    kl.reenableKeyguard();   }  } } @Override public void onNotificationRemoved(StatusBarNotification sbn) {  super.onNotificationRemoved(sbn); }} 

主的activity,注釋在代碼中了,就不詳細說了 

public class MainActivity extends AppCompatActivity implements CompoundButton  .OnCheckedChangeListener, View.OnClickListener,SeekBar.OnSeekBarChangeListener { private LinearLayout root; private CheckBox isMusic; private CheckBox isUnlock; private SharedPreferences.Editor editor; private SharedPreferences sharedPreferences; private Button setPermision; private SeekBar seekBar; private AudioManager audioManager; @Override protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  // 擷取控制項執行個體  root = (LinearLayout) findViewById(R.id.root);  isMusic = (CheckBox) findViewById(R.id.isMusic);  isUnlock = (CheckBox) findViewById(R.id.isUnlock);  setPermision = (Button) findViewById(R.id.setPermision);  seekBar = (SeekBar) findViewById(R.id.seekbar);  // 註冊監聽  isMusic.setOnCheckedChangeListener(this);  isUnlock.setOnCheckedChangeListener(this);  setPermision.setOnClickListener(this);  seekBar.setOnSeekBarChangeListener(this);  // 讀取設定資訊  sharedPreferences = getSharedPreferences("userdata", MODE_PRIVATE);  editor = sharedPreferences.edit();  boolean music = sharedPreferences.getBoolean("isMusic", true);  boolean unlock = sharedPreferences.getBoolean("isUnlock", true);  isMusic.setChecked(music);  isUnlock.setChecked(unlock);  // 獲得Audiomanager,控制系統音量  audioManager = (AudioManager) getSystemService(this.AUDIO_SERVICE);  seekBar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));  seekBar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));  // 監聽系統媒體音量改變,並改變介面上的Seekbar的進度  IntentFilter intentFilter = new IntentFilter();  intentFilter.addAction("android.media.VOLUME_CHANGED_ACTION");  VolumReceiver receiver = new VolumReceiver();  registerReceiver(receiver,intentFilter);  // 開啟服務  Intent intent = new Intent(MainActivity.this, NotificationService.class);  startService(intent); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) {  // 判斷返回鍵點擊,提示使用者是否確認退出  if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {   Snackbar snackbar = Snackbar.make(root, "退出軟體", Snackbar.LENGTH_LONG)     .setAction("確認", new View.OnClickListener() {      @Override      public void onClick(View v) {       MainActivity.this.finish();      }     });   snackbar.show();   return true;  }  return super.onKeyDown(keyCode, event); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {  // checkbox的點擊監聽  switch (buttonView.getId()) {   case R.id.isMusic:    editor.putBoolean("isMusic", isChecked);    editor.commit();    break;   case R.id.isUnlock:    editor.putBoolean("isUnlock", isChecked);    editor.commit();    break;  } } @Override public void onClick(View v) {  switch (v.getId()){   case R.id.setPermision:    // 開啟系統裡面的服務,方便使用者直接賦予許可權    Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);    startActivity(intent);    break;  } } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) {  // seekbar的監聽,滑動停止就修改系統媒體音量  audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,seekBar.getProgress(),0); } // 音量廣播接收 class VolumReceiver extends BroadcastReceiver{  @Override  public void onReceive(Context context, Intent intent) {   seekBar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));  } }} 

Mainfest 

<?xml version="1.0" encoding="utf-8"?><manifest package="com.fndroid.administrator.justforyou"   xmlns:android="http://schemas.android.com/apk/res/android"> <uses-permission android:name="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"/> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <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>  <service android:name=".NotificationService"     android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">   <intent-filter>    <action android:name="android.service.notification.NotificationListenerService" />   </intent-filter>  </service> </application></manifest> 

gradle添加依賴,因為用了Snackbar 

dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1'}

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.