質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Q&A

解決済

1回答

3430閲覧

android8.0以降のバイブを実装したserviceでバイブが止まってしまう

yuba_yuba

総合スコア44

Android

Androidは、Google社が開発したスマートフォンやタブレットなど携帯端末向けのプラットフォームです。 カーネル・ミドルウェア・ユーザーインターフェイス・ウェブブラウザ・電話帳などのアプリケーションやソフトウェアをひとつにまとめて構成。 カーネル・ライブラリ・ランタイムはほとんどがC言語/C++、アプリケーションなどはJavaSEのサブセットとAndroid環境で書かれています。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

0グッド

1クリップ

投稿2019/02/02 06:09

アラーム機能を実装したアプリを作っています
そのアプリでserviceを使っているのですがバックキーやホームキーなどを押してアプリがバックグラウンドに回る、もしくは別のバイブを起動するとserviceのバイブが停止してしまいます
android8.0より前の実装は想定通りに動いたのですが、8.0以降だと意図しない動作となってしまいます
サービスが生きている限りはバイブし続けさせるにはどのように実装すればよいでしょうか?
よろしくお願いいたします

以下がコードになります

MainActivity.Java

java

1import android.content.Intent; 2import android.os.VibrationEffect; 3import android.os.Vibrator; 4import android.support.v7.app.AppCompatActivity; 5import android.os.Bundle; 6import android.view.View; 7import android.widget.Button; 8 9 10public class MainActivity extends AppCompatActivity { 11 12 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 18 19 Button start=findViewById(R.id.button); 20 start.setOnClickListener(new View.OnClickListener() { 21 @Override 22 public void onClick(View view) { 23 Intent intent2 = new Intent(getApplication(), AlarmService.class); 24 startService(intent2); 25 } 26 }); 27 28 Button stop=findViewById(R.id.button2); 29 stop.setOnClickListener(new View.OnClickListener() { 30 @Override 31 public void onClick(View view) { 32 Intent intent = new Intent(getApplication(), AlarmService.class); 33 stopService(intent); 34 } 35 }); 36 37 38 39 Button vib=findViewById(R.id.button3); 40 vib.setOnClickListener(new View.OnClickListener() { 41 @Override 42 public void onClick(View view) { 43 long pattern[] = {1000, 1000 }; 44 Vibrator vib = (Vibrator)getSystemService(VIBRATOR_SERVICE); 45 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { 46 int[] anp={0, VibrationEffect.DEFAULT_AMPLITUDE}; 47 VibrationEffect vibrationEffect=VibrationEffect.createWaveform(pattern,anp,-1); 48 if (vib != null) { 49 vib.vibrate(vibrationEffect); 50 } 51 }else { 52 if(vib!=null){ 53 vib.vibrate(pattern,0); 54 } 55 } 56 } 57 }); 58 59 } 60}

AlarmService.Java

java

1import android.app.Notification; 2import android.app.NotificationChannel; 3import android.app.NotificationManager; 4import android.app.PendingIntent; 5import android.app.Service; 6import android.content.Context; 7import android.content.Intent; 8import android.graphics.Color; 9import android.os.IBinder; 10import android.os.VibrationEffect; 11import android.os.Vibrator; 12import android.support.annotation.Nullable; 13import android.support.v4.app.NotificationCompat; 14import android.support.v4.app.NotificationManagerCompat; 15 16public class AlarmService extends Service { 17 18 private Vibrator vib; 19 @Override 20 public int onStartCommand(Intent intent, int flags, int startId) { 21 long pattern[] = {1000, 1000 }; 22 Intent intent1 = new Intent(this,MainActivity.class); 23 intent1.addCategory(Intent.CATEGORY_LAUNCHER); 24 intent1.setClassName(this.getPackageName(), MainActivity.class.getName()); 25 intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK); 26 PendingIntent pendingIntent = 27 PendingIntent.getActivity(this,0, intent1, PendingIntent.FLAG_UPDATE_CURRENT); 28 29 String channelId = "default"; 30 String text="サービスが起動しています"; 31 32 vib = (Vibrator)getSystemService(VIBRATOR_SERVICE); 33 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { 34 int[] anp={0,VibrationEffect.DEFAULT_AMPLITUDE}; 35 VibrationEffect vibrationEffect=VibrationEffect.createWaveform(pattern,anp,0); 36 NotificationManager notificationManager; 37 38 notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); 39 NotificationChannel channel =new NotificationChannel( 40 channelId, getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT); 41 channel.setSound(null,null); 42 channel.setDescription(text); 43 channel.enableLights(true); 44 channel.setLightColor(Color.BLUE); 45 channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); 46 channel.setShowBadge(true); 47 48 if (notificationManager != null) { 49 notificationManager.createNotificationChannel(channel); 50 51 Notification notification = new Notification.Builder(this, channelId) 52 .setContentTitle(getString(R.string.app_name)) 53 .setSmallIcon(R.mipmap.ic_launcher) 54 .setContentText(text) 55 .setAutoCancel(false) 56 .setContentIntent(pendingIntent) 57 .setTicker(text) 58 .setWhen(System.currentTimeMillis()) 59 .build(); 60 notification.flags = Notification.FLAG_ONGOING_EVENT; 61 62 63 startForeground(1, notification); 64 } 65 if (vib != null) { 66 vib.vibrate(vibrationEffect); 67 } 68 }else { 69 NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); 70 builder.setSmallIcon(R.mipmap.ic_launcher); 71 72 builder.setContentTitle(getString(R.string.app_name)); 73 builder.setContentText(text); 74 builder.setPriority(2); 75 builder.setContentIntent(pendingIntent); 76 builder.setWhen(System.currentTimeMillis()); 77 78 builder.setAutoCancel(true); 79 builder.setTicker(text); 80 NotificationManagerCompat manager; 81 manager = NotificationManagerCompat.from(getApplicationContext()); 82 Notification notification=builder.build(); 83 notification.flags=Notification.FLAG_ONGOING_EVENT; 84 manager.notify(getString(R.string.app_name),1, notification); 85 86 if(vib!=null){ 87 vib.vibrate(pattern,0); 88 } 89 90 91 92 } 93 return START_NOT_STICKY; 94 95 } 96 97 @Override 98 public void onDestroy() { 99 super.onDestroy(); 100 101 NotificationManager notificationManager; 102 NotificationManagerCompat manager; 103 notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); 104 manager = NotificationManagerCompat.from(getApplicationContext()); 105 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { 106 if (notificationManager != null) { 107 notificationManager.cancel(R.string.app_name); 108 } 109 }else { 110 manager.cancel(getString(R.string.app_name),1); 111 } 112 113 vib.cancel(); 114 vib=null; 115 116 } 117 118 119 120 121 122 @Nullable 123 @Override 124 public IBinder onBind(Intent intent) { 125 return null; 126 } 127}

activity_main.xml

xml

1<?xml version="1.0" encoding="utf-8"?> 2<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 tools:context=".MainActivity"> 8 9 <ScrollView 10 android:layout_width="match_parent" 11 android:layout_height="match_parent" 12 android:layout_above="@+id/button" 13 android:layout_below="@+id/button"> 14 15 <LinearLayout 16 android:layout_width="match_parent" 17 android:layout_height="wrap_content" 18 android:orientation="vertical" /> 19 </ScrollView> 20 21 <TextView 22 android:id="@+id/text" 23 android:layout_width="match_parent" 24 android:layout_height="match_parent" 25 app:layout_constraintBottom_toBottomOf="parent" 26 app:layout_constraintLeft_toLeftOf="parent" 27 app:layout_constraintRight_toRightOf="parent" 28 app:layout_constraintTop_toTopOf="parent" /> 29 30 <Button 31 android:id="@+id/button" 32 android:layout_width="wrap_content" 33 android:layout_height="wrap_content" 34 android:layout_alignParentBottom="false" 35 android:text="start" /> 36 37 <Button 38 android:id="@+id/button2" 39 android:layout_width="wrap_content" 40 android:layout_height="wrap_content" 41 android:layout_below="@+id/button" 42 android:layout_alignParentRight="false" 43 android:layout_alignParentBottom="false" 44 android:text="stop" /> 45 46 <Button 47 android:id="@+id/button3" 48 android:layout_width="wrap_content" 49 android:layout_height="wrap_content" 50 android:layout_below="@+id/button2" 51 android:text="VIB" /> 52 53</RelativeLayout>

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

もっと良い方法があるかもしれませんが、一応解決致しました。
サービスでhandlerを使い単発バイブを回す、といった感じです

AlarmService.java

java

1import android.app.Notification; 2import android.app.NotificationChannel; 3import android.app.NotificationManager; 4import android.app.PendingIntent; 5import android.app.Service; 6import android.content.Context; 7import android.content.Intent; 8import android.graphics.Color; 9import android.media.AudioAttributes; 10import android.os.Handler; 11import android.os.IBinder; 12import android.os.VibrationEffect; 13import android.os.Vibrator; 14import android.support.annotation.Nullable; 15import android.support.v4.app.NotificationCompat; 16import android.support.v4.app.NotificationManagerCompat; 17 18public class AlarmService extends Service { 19 private Handler handler = new Handler(); 20 private Runnable runnable = new Runnable() { 21 @Override 22 public void run() { 23 vibOn(); 24 handler.postDelayed(this, 2000); 25 } 26 }; 27 private Vibrator vib; 28 private long pattern[] = {1000, 1000 }; 29 private VibrationEffect vibrationEffect; 30 @Override 31 public int onStartCommand(Intent intent, int flags, int startId) { 32 33 Intent intent1 = new Intent(this,MainActivity.class); 34 intent1.addCategory(Intent.CATEGORY_LAUNCHER); 35 intent1.setClassName(this.getPackageName(), MainActivity.class.getName()); 36 intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK); 37 PendingIntent pendingIntent = 38 PendingIntent.getActivity(this,0, intent1, PendingIntent.FLAG_UPDATE_CURRENT); 39 40 String channelId = "default"; 41 String text="サービスが起動しています"; 42 43 vib = (Vibrator)getSystemService(VIBRATOR_SERVICE); 44 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { 45 int[] anp={0,VibrationEffect.DEFAULT_AMPLITUDE}; 46 vibrationEffect=VibrationEffect.createWaveform(pattern,anp,-1); 47 NotificationManager notificationManager; 48 49 notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); 50 NotificationChannel channel =new NotificationChannel( 51 channelId, getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT); 52 channel.setSound(null,null); 53 channel.setDescription(text); 54 channel.enableLights(true); 55 channel.setLightColor(Color.BLUE); 56 channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE); 57 channel.setShowBadge(true); 58 59 if (notificationManager != null) { 60 notificationManager.createNotificationChannel(channel); 61 62 Notification notification = new Notification.Builder(this, channelId) 63 .setContentTitle(getString(R.string.app_name)) 64 .setSmallIcon(R.mipmap.ic_launcher) 65 .setContentText(text) 66 .setAutoCancel(false) 67 .setContentIntent(pendingIntent) 68 .setTicker(text) 69 .setWhen(System.currentTimeMillis()) 70 .build(); 71 notification.flags = Notification.FLAG_ONGOING_EVENT; 72 73 74 startForeground(1, notification); 75 } 76 77 78 }else { 79 NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext()); 80 builder.setSmallIcon(R.mipmap.ic_launcher); 81 82 builder.setContentTitle(getString(R.string.app_name)); 83 builder.setContentText(text); 84 builder.setPriority(2); 85 builder.setContentIntent(pendingIntent); 86 builder.setWhen(System.currentTimeMillis()); 87 88 builder.setAutoCancel(true); 89 builder.setTicker(text); 90 NotificationManagerCompat manager; 91 manager = NotificationManagerCompat.from(getApplicationContext()); 92 Notification notification=builder.build(); 93 notification.flags=Notification.FLAG_ONGOING_EVENT; 94 manager.notify(getString(R.string.app_name),1, notification); 95 96 } 97 98 handler.post(runnable); 99 100 return START_NOT_STICKY; 101 102 } 103 104 private void vibOn(){ 105 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O){ 106 if (vib != null) { 107 vib.vibrate(vibrationEffect); 108 } 109 }else { 110 if(vib!=null){ 111 vib.vibrate(pattern,0); 112 } 113 114 } 115 } 116 117 @Override 118 public void onDestroy() { 119 super.onDestroy(); 120 121 NotificationManager notificationManager; 122 NotificationManagerCompat manager; 123 notificationManager = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE); 124 manager = NotificationManagerCompat.from(getApplicationContext()); 125 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { 126 if (notificationManager != null) { 127 notificationManager.cancel(R.string.app_name); 128 } 129 }else { 130 manager.cancel(getString(R.string.app_name),1); 131 } 132 133 vib.cancel(); 134 vib=null; 135 136 } 137 138 139 140 141 142 @Nullable 143 @Override 144 public IBinder onBind(Intent intent) { 145 return null; 146 } 147}

投稿2019/02/05 11:32

yuba_yuba

総合スコア44

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問